1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.javascript.polyfill;
16
17 import java.io.IOException;
18 import java.nio.charset.StandardCharsets;
19 import java.util.HashMap;
20 import java.util.Map;
21
22 import org.apache.commons.io.IOUtils;
23 import org.htmlunit.corejs.javascript.Context;
24 import org.htmlunit.corejs.javascript.Script;
25 import org.htmlunit.corejs.javascript.Scriptable;
26
27
28
29
30
31
32
33 public class Polyfill {
34
35 private static final Map<String, Polyfill> CACHE = new HashMap<>();
36
37 private String url_;
38 private String source_;
39 private Script script_;
40
41
42
43
44
45 public static Polyfill getFetchPolyfill() throws IOException {
46 return getPolyfill("fetch/fetch.umd.js");
47 }
48
49 private static Polyfill getPolyfill(final String resouceName) throws IOException {
50 Polyfill poly = CACHE.get(resouceName);
51 if (poly != null) {
52 return poly;
53 }
54
55 poly = new Polyfill();
56 poly.source_ = IOUtils.toString(poly.getClass().getResourceAsStream(resouceName), StandardCharsets.UTF_8);
57 poly.url_ = poly.getClass().getResource(resouceName).toExternalForm();
58
59 CACHE.put(resouceName, poly);
60 return poly;
61 }
62
63
64
65
66
67
68
69 public void apply(final Context context, final Scriptable scriptable) {
70 if (script_ == null) {
71 script_ = context.compileString(source_, url_, 0, null);
72 }
73
74 if (script_ != null) {
75 script_.exec(context, scriptable);
76 }
77 }
78 }