1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.javascript;
16
17 import static org.htmlunit.BrowserVersionFeatures.JS_ERROR_STACK_TRACE_LIMIT;
18 import static org.htmlunit.BrowserVersionFeatures.JS_ERROR_STACK_TRACE_LIMIT_128;
19 import static org.htmlunit.BrowserVersionFeatures.JS_WINDOW_INSTALL_TRIGGER_NULL;
20
21 import java.io.IOException;
22 import java.io.ObjectInputStream;
23 import java.lang.reflect.Member;
24 import java.lang.reflect.Method;
25 import java.net.URL;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.function.Consumer;
32
33 import org.apache.commons.logging.Log;
34 import org.apache.commons.logging.LogFactory;
35 import org.htmlunit.BrowserVersion;
36 import org.htmlunit.Page;
37 import org.htmlunit.ScriptException;
38 import org.htmlunit.WebAssert;
39 import org.htmlunit.WebClient;
40 import org.htmlunit.WebWindow;
41 import org.htmlunit.corejs.javascript.AbstractEcmaObjectOperations;
42 import org.htmlunit.corejs.javascript.BaseFunction;
43 import org.htmlunit.corejs.javascript.Callable;
44 import org.htmlunit.corejs.javascript.Context;
45 import org.htmlunit.corejs.javascript.ContextAction;
46 import org.htmlunit.corejs.javascript.ContextFactory;
47 import org.htmlunit.corejs.javascript.EcmaError;
48 import org.htmlunit.corejs.javascript.Function;
49 import org.htmlunit.corejs.javascript.FunctionObject;
50 import org.htmlunit.corejs.javascript.IteratorLikeIterable;
51 import org.htmlunit.corejs.javascript.JavaScriptException;
52 import org.htmlunit.corejs.javascript.NativeArray;
53 import org.htmlunit.corejs.javascript.NativeArrayIterator;
54 import org.htmlunit.corejs.javascript.NativeConsole;
55 import org.htmlunit.corejs.javascript.NativeObject;
56 import org.htmlunit.corejs.javascript.RhinoException;
57 import org.htmlunit.corejs.javascript.Script;
58 import org.htmlunit.corejs.javascript.ScriptRuntime;
59 import org.htmlunit.corejs.javascript.Scriptable;
60 import org.htmlunit.corejs.javascript.ScriptableObject;
61 import org.htmlunit.corejs.javascript.StackStyle;
62 import org.htmlunit.corejs.javascript.Symbol;
63 import org.htmlunit.corejs.javascript.SymbolKey;
64 import org.htmlunit.corejs.javascript.TopLevel;
65 import org.htmlunit.corejs.javascript.VarScope;
66 import org.htmlunit.corejs.javascript.WithScope;
67 import org.htmlunit.corejs.javascript.typedarrays.NativeArrayBuffer;
68 import org.htmlunit.corejs.javascript.typedarrays.NativeUint8Array;
69 import org.htmlunit.html.DomNode;
70 import org.htmlunit.html.HtmlElement;
71 import org.htmlunit.html.HtmlForm;
72 import org.htmlunit.html.HtmlPage;
73 import org.htmlunit.html.SubmittableElement;
74 import org.htmlunit.html.csp.ContentSecurityPolicy;
75 import org.htmlunit.javascript.background.BackgroundJavaScriptFactory;
76 import org.htmlunit.javascript.background.JavaScriptExecutor;
77 import org.htmlunit.javascript.configuration.AbstractJavaScriptConfiguration;
78 import org.htmlunit.javascript.configuration.ClassConfiguration;
79 import org.htmlunit.javascript.configuration.ClassConfiguration.ConstantInfo;
80 import org.htmlunit.javascript.configuration.ClassConfiguration.PropertyInfo;
81 import org.htmlunit.javascript.configuration.JavaScriptConfiguration;
82 import org.htmlunit.javascript.configuration.ProxyAutoConfigJavaScriptConfiguration;
83 import org.htmlunit.javascript.host.ConsoleCustom;
84 import org.htmlunit.javascript.host.URLSearchParams;
85 import org.htmlunit.javascript.host.Window;
86 import org.htmlunit.javascript.host.WindowOrWorkerGlobalScope;
87 import org.htmlunit.javascript.host.dom.DOMException;
88 import org.htmlunit.javascript.host.fetch.Headers;
89 import org.htmlunit.javascript.host.html.HTMLElement;
90 import org.htmlunit.javascript.host.html.HTMLImageElement;
91 import org.htmlunit.javascript.host.html.HTMLOptionElement;
92 import org.htmlunit.javascript.host.intl.Intl;
93 import org.htmlunit.javascript.host.worker.WorkerGlobalScope;
94 import org.htmlunit.javascript.host.xml.FormData;
95 import org.htmlunit.javascript.polyfill.Polyfill;
96 import org.htmlunit.util.SerializableLock;
97 import org.htmlunit.util.StringUtils;
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124 public class JavaScriptEngine implements AbstractJavaScriptEngine<Script> {
125
126 private static final Log LOG = LogFactory.getLog(JavaScriptEngine.class);
127
128 private static final String SANDBOX_ALLOW_SCRIPTS = "allow-scripts";
129
130
131 public static final Object[] EMPTY_ARGS = ScriptRuntime.emptyArgs;
132
133
134 public static final Object UNDEFINED = org.htmlunit.corejs.javascript.Undefined.instance;
135
136 private WebClient webClient_;
137 private HtmlUnitContextFactory contextFactory_;
138 private JavaScriptConfiguration jsConfig_;
139
140 private transient ThreadLocal<Boolean> javaScriptRunning_;
141 private transient ThreadLocal<List<PostponedAction>> postponedActions_;
142
143
144 private transient ThreadLocal<Boolean> holdPostponedActions_;
145
146 private transient volatile boolean shutdownPending_;
147
148
149 private transient volatile JavaScriptExecutor javaScriptExecutor_;
150
151 private final SerializableLock javaScriptExecutorLock_ = new SerializableLock();
152
153
154
155
156
157 public static final String KEY_STARTING_PAGE = "startingPage";
158
159
160
161
162
163 static final String KEY_RUNNING_PAGE = "runningPage";
164
165
166
167
168
169
170 public JavaScriptEngine(final WebClient webClient) {
171 if (webClient == null) {
172 throw new IllegalArgumentException("JavaScriptEngine ctor requires a webClient");
173 }
174
175 webClient_ = webClient;
176 contextFactory_ = new HtmlUnitContextFactory(webClient);
177 initTransientFields();
178
179 jsConfig_ = JavaScriptConfiguration.getInstance(webClient.getBrowserVersion());
180 RhinoException.setStackStyle(StackStyle.MOZILLA_LF);
181 }
182
183
184
185
186
187 private WebClient getWebClient() {
188 return webClient_;
189 }
190
191
192
193
194 @Override
195 public HtmlUnitContextFactory getContextFactory() {
196 return contextFactory_;
197 }
198
199
200
201
202
203 @Override
204 public void initialize(final WebWindow webWindow, final Page page) {
205 WebAssert.notNull("webWindow", webWindow);
206
207 if (shutdownPending_) {
208 return;
209 }
210
211 getContextFactory().call(cx -> {
212 try {
213 init(webWindow, page, cx);
214 }
215 catch (final Exception e) {
216 LOG.error("Exception while initializing JavaScript for the page", e);
217 throw new ScriptException(null, e);
218 }
219 return null;
220 });
221 }
222
223
224
225
226
227
228 public JavaScriptExecutor getJavaScriptExecutor() {
229 return javaScriptExecutor_;
230 }
231
232
233
234
235
236
237
238 private void init(final WebWindow webWindow, final Page page, final Context cx) throws Exception {
239 final WebClient webClient = getWebClient();
240 final BrowserVersion browserVersion = webClient.getBrowserVersion();
241
242 final Window jsWindow = new Window();
243 jsWindow.setClassName("Window");
244
245 final TopLevel scope = cx.initSafeStandardObjects(new TopLevel(jsWindow));
246 jsWindow.setParentScope(scope);
247 configureRhino(webClient, browserVersion, scope, jsWindow);
248
249 final Map<Class<? extends Scriptable>, Scriptable> prototypes = new HashMap<>();
250 final Map<String, Scriptable> prototypesPerJSName = new HashMap<>();
251
252 final ClassConfiguration windowConfig = jsConfig_.getWindowClassConfiguration();
253 final FunctionObject functionObject = new FunctionObject(jsWindow.getClassName(), windowConfig.getJsConstructor().getValue(), scope);
254 ScriptableObject.defineProperty(jsWindow, "constructor", functionObject,
255 ScriptableObject.DONTENUM | ScriptableObject.PERMANENT | ScriptableObject.READONLY);
256
257 configureConstantsPropertiesAndFunctions(windowConfig, scope, jsWindow);
258
259 final HtmlUnitScriptable windowPrototype = configureClass(windowConfig, scope);
260 jsWindow.setPrototype(windowPrototype);
261 prototypes.put(windowConfig.getHostClass(), windowPrototype);
262 prototypesPerJSName.put(windowConfig.getClassName(), windowPrototype);
263
264 configureGlobalThis(scope, jsWindow, windowConfig, functionObject, jsConfig_, browserVersion, prototypes, prototypesPerJSName);
265
266
267 URLSearchParams.NativeParamsIterator.init(cx, scope, "URLSearchParams Iterator");
268 FormData.FormDataIterator.init(cx, scope, "FormData Iterator");
269 Headers.HeadersIterator.init(cx, scope);
270
271
272
273
274
275
276 if (browserVersion.hasFeature(JS_WINDOW_INSTALL_TRIGGER_NULL)) {
277 jsWindow.put("InstallTrigger", jsWindow, null);
278 }
279
280
281 final Method imageCtor = HTMLImageElement.class.getDeclaredMethod("jsConstructorImage");
282 additionalCtor(scope, jsWindow, prototypesPerJSName.get("HTMLImageElement"), imageCtor, "Image", "HTMLImageElement");
283 final Method optionCtor = HTMLOptionElement.class.getDeclaredMethod("jsConstructorOption",
284 Object.class, String.class, boolean.class, boolean.class);
285 additionalCtor(scope, jsWindow, prototypesPerJSName.get("HTMLOptionElement"), optionCtor, "Option", "HTMLOptionElement");
286
287 if (!webClient.getOptions().isWebSocketEnabled()) {
288 deleteProperties(jsWindow, "WebSocket");
289 }
290
291 jsWindow.setPrototypes(prototypes);
292 jsWindow.initialize(scope, webWindow, page);
293
294 applyPolyfills(webClient, browserVersion, cx, scope, jsWindow);
295 }
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310 public static void configureGlobalThis(
311 final TopLevel scope,
312 final HtmlUnitScriptable globalThis,
313 final ClassConfiguration scopeConfig,
314 final FunctionObject scopeContructorFunctionObject,
315 final AbstractJavaScriptConfiguration jsConfig,
316 final BrowserVersion browserVersion,
317 final Map<Class<? extends Scriptable>, Scriptable> prototypes,
318 final Map<String, Scriptable> prototypesPerJSName) throws Exception {
319
320 final Scriptable objectPrototype = ScriptableObject.getObjectPrototype(scope);
321
322 final Map<String, Function> ctorPrototypesPerJSName = new HashMap<>();
323 for (final ClassConfiguration config : jsConfig.getAll()) {
324 final String jsClassName = config.getClassName();
325 Scriptable prototype = prototypesPerJSName.get(jsClassName);
326 final String extendedClassName =
327 StringUtils.isEmptyOrNull(config.getExtendedClassName()) ? null : config.getExtendedClassName();
328
329
330 if (config == scopeConfig) {
331 if (extendedClassName == null) {
332 prototype.setPrototype(objectPrototype);
333 }
334 else {
335 prototype.setPrototype(prototypesPerJSName.get(extendedClassName));
336 }
337
338
339 addAsConstructorAndAlias(scopeContructorFunctionObject, scope, globalThis, prototype, config);
340 configureConstantsStaticPropertiesAndStaticFunctions(config, scope, scopeContructorFunctionObject);
341
342
343 if (extendedClassName != null) {
344 scopeContructorFunctionObject.setPrototype(ctorPrototypesPerJSName.get(extendedClassName));
345 }
346 }
347 else {
348 final HtmlUnitScriptable classPrototype = configureClass(config, scope);
349 prototypes.put(config.getHostClass(), classPrototype);
350 prototypesPerJSName.put(jsClassName, classPrototype);
351 prototype = classPrototype;
352
353 if (extendedClassName == null) {
354 classPrototype.setPrototype(objectPrototype);
355 }
356 else {
357 classPrototype.setPrototype(prototypesPerJSName.get(extendedClassName));
358 }
359
360
361 if (prototype != null) {
362 final Map.Entry<String, Member> jsConstructor = config.getJsConstructor();
363 if (jsConstructor == null) {
364 final HtmlUnitScriptable constructor = config.getHostClass().getDeclaredConstructor().newInstance();
365 constructor.setClassName(jsClassName);
366 defineConstructor(scope, prototype, constructor);
367 configureConstantsStaticPropertiesAndStaticFunctions(config, scope, constructor);
368
369 if (config.isJsObject()) {
370 globalThis.defineProperty(jsClassName, constructor, ScriptableObject.DONTENUM);
371 }
372 }
373 else {
374 final FunctionObject function = new FunctionObject(jsConstructor.getKey(), jsConstructor.getValue(), scope);
375 ctorPrototypesPerJSName.put(jsClassName, function);
376
377 addAsConstructorAndAlias(function, scope, globalThis, prototype, config);
378 configureConstantsStaticPropertiesAndStaticFunctions(config, scope, function);
379
380 if (!config.isJsObject()) {
381
382
383
384 globalThis.delete(prototype.getClassName());
385 }
386
387
388 if (extendedClassName != null) {
389 function.setPrototype(ctorPrototypesPerJSName.get(extendedClassName));
390 }
391 }
392 }
393 }
394 }
395 }
396
397 private static void addAsConstructorAndAlias(final FunctionObject function,
398 final VarScope scope,
399 final HtmlUnitScriptable destination,
400 final Scriptable prototype,
401 final ClassConfiguration config) {
402 try {
403 function.addAsConstructor(scope, prototype, ScriptableObject.DONTENUM);
404
405 final String alias = config.getJsConstructorAlias();
406 if (alias != null) {
407 ScriptableObject.defineProperty(destination, alias, function, ScriptableObject.DONTENUM);
408 }
409 }
410 catch (final Exception e) {
411
412 if (LOG.isWarnEnabled()) {
413 final String newline = System.lineSeparator();
414 LOG.warn("Error during JavaScriptEngine.init(WebWindow, Context)" + newline
415 + e.getMessage() + newline
416 + "prototype: " + prototype.getClassName(), e);
417 }
418 }
419 }
420
421 private static void additionalCtor(final VarScope scope, final Window window, final Scriptable proto,
422 final Method ctorMethod, final String prop, final String clazzName) throws Exception {
423 final FunctionObject function = new FunctionObject(prop, ctorMethod, scope);
424 final Object prototypeProperty = ScriptableObject.getProperty(window, clazzName);
425 try {
426 function.addAsConstructor(scope, proto, ScriptableObject.DONTENUM);
427 }
428 catch (final Exception e) {
429
430 if (LOG.isWarnEnabled()) {
431 final String newline = System.lineSeparator();
432 LOG.warn("Error during JavaScriptEngine.init(WebWindow, Context)" + newline
433 + e.getMessage() + newline
434 + "prototype: " + proto.getClassName(), e);
435 }
436 }
437 ScriptableObject.defineProperty(window, prop, function, ScriptableObject.DONTENUM);
438 ScriptableObject.defineProperty(window, clazzName, prototypeProperty, ScriptableObject.DONTENUM);
439 }
440
441
442
443
444
445
446
447
448
449 public static void configureRhino(final WebClient webClient, final BrowserVersion browserVersion,
450 final TopLevel scope, final HtmlUnitScriptable globalThis) {
451
452
453
454
455 NativeConsole.init(scope, false, webClient.getWebConsole());
456
457
458
459 final ScriptableObject console = (ScriptableObject) ScriptableObject.getProperty(globalThis, "console");
460 console.defineFunctionProperties(scope, new String[] {"timeStamp"}, ConsoleCustom.class, ScriptableObject.DONTENUM);
461
462
463 deleteProperties(globalThis, "Continuation", "StopIteration", "uneval", "global", "__GeneratorFunction", "SharedArrayBuffer");
464
465
466 final ScriptableObject stringPrototype = (ScriptableObject) ScriptableObject.getClassPrototype(scope, "String");
467 deleteProperties(stringPrototype, "equals", "equalsIgnoreCase", "toSource");
468
469 final ScriptableObject numberPrototype = (ScriptableObject) ScriptableObject.getClassPrototype(scope, "Number");
470 deleteProperties(numberPrototype, "toSource");
471 final ScriptableObject datePrototype = (ScriptableObject) ScriptableObject.getClassPrototype(scope, "Date");
472 deleteProperties(datePrototype, "toSource");
473
474 removePrototypeProperties(scope, "Object", "toSource");
475 removePrototypeProperties(scope, "Array", "toSource");
476 removePrototypeProperties(scope, "Function", "toSource");
477
478 deleteProperties(globalThis, "isXMLName");
479
480 NativeFunctionToStringFunction.installFix(scope, browserVersion);
481
482 final ScriptableObject errorObject = (ScriptableObject) ScriptableObject.getProperty(globalThis, "Error");
483 if (browserVersion.hasFeature(JS_ERROR_STACK_TRACE_LIMIT)) {
484 errorObject.defineProperty("stackTraceLimit", 10, ScriptableObject.EMPTY);
485 }
486 else if (browserVersion.hasFeature(JS_ERROR_STACK_TRACE_LIMIT_128)) {
487 errorObject.defineProperty("stackTraceLimit", 128, ScriptableObject.EMPTY);
488 }
489
490
491 Intl.init(scope, globalThis, browserVersion);
492 }
493
494
495
496
497
498
499
500
501
502
503
504 public static void applyPolyfills(final WebClient webClient, final BrowserVersion browserVersion,
505 final Context context, final VarScope scope, final HtmlUnitScriptable scriptable) throws IOException {
506
507 if (webClient.getOptions().isFetchPolyfillEnabled()) {
508
509 scriptable.put("fetch", scriptable, UNDEFINED);
510 Polyfill.getFetchPolyfill().apply(context, scope, scriptable);
511 }
512 }
513
514 private static void defineConstructor(final VarScope scope,
515 final Scriptable prototype, final ScriptableObject constructor) {
516 constructor.setParentScope(scope);
517 try {
518 ScriptableObject.defineProperty(prototype, "constructor", constructor,
519 ScriptableObject.DONTENUM | ScriptableObject.PERMANENT | ScriptableObject.READONLY);
520 }
521 catch (final Exception e) {
522
523 if (LOG.isWarnEnabled()) {
524 final String newline = System.lineSeparator();
525 LOG.warn("Error during JavaScriptEngine.init(WebWindow, Context)" + newline
526 + e.getMessage() + newline
527 + "prototype: " + prototype.getClassName(), e);
528 }
529 }
530
531 try {
532 ScriptableObject.defineProperty(constructor, "prototype", prototype,
533 ScriptableObject.DONTENUM | ScriptableObject.PERMANENT | ScriptableObject.READONLY);
534 }
535 catch (final Exception e) {
536
537 if (LOG.isWarnEnabled()) {
538 final String newline = System.lineSeparator();
539 LOG.warn("Error during JavaScriptEngine.init(WebWindow, Context)" + newline
540 + e.getMessage() + newline
541 + "prototype: " + prototype.getClassName(), e);
542 }
543 }
544 }
545
546
547
548
549
550
551 private static void deleteProperties(final Scriptable destination, final String... propertiesToDelete) {
552 for (final String property : propertiesToDelete) {
553 destination.delete(property);
554 }
555 }
556
557
558
559
560
561
562
563 private static void removePrototypeProperties(final VarScope scope, final String className,
564 final String... properties) {
565 final ScriptableObject prototype = (ScriptableObject) ScriptableObject.getClassPrototype(scope, className);
566 for (final String property : properties) {
567 prototype.delete(property);
568 }
569 }
570
571
572
573
574
575
576
577
578
579
580 public static HtmlUnitScriptable configureClass(final ClassConfiguration config,
581 final TopLevel scope)
582 throws Exception {
583
584 final HtmlUnitScriptable prototype = config.getHostClass().getDeclaredConstructor().newInstance();
585 prototype.setParentScope(scope);
586 prototype.setClassName(config.getClassName());
587
588 configureConstantsPropertiesAndFunctions(config, scope, prototype);
589
590 return prototype;
591 }
592
593
594
595
596
597
598 private static void configureConstantsStaticPropertiesAndStaticFunctions(final ClassConfiguration config,
599 final TopLevel scope, final ScriptableObject scriptable) {
600 configureConstants(config, scriptable);
601 configureStaticProperties(config, scope, scriptable);
602 configureStaticFunctions(config, scope, scriptable);
603 }
604
605
606
607
608
609
610
611 private static void configureConstantsPropertiesAndFunctions(final ClassConfiguration config,
612 final TopLevel scope, final ScriptableObject scriptable) {
613 configureConstants(config, scriptable);
614 configureProperties(config, scope, scriptable);
615 configureFunctions(config, scope, scriptable);
616 configureSymbolConstants(config, scriptable);
617 configureSymbols(config, scope, scriptable);
618 }
619
620 private static void configureFunctions(final ClassConfiguration config,
621 final TopLevel scope, final ScriptableObject scriptable) {
622
623 final Map<String, Method> functionMap = config.getFunctionMap();
624 if (functionMap != null) {
625 for (final Entry<String, Method> functionInfo : functionMap.entrySet()) {
626 final String functionName = functionInfo.getKey();
627 final Method method = functionInfo.getValue();
628 final FunctionObject functionObject = new FunctionObject(functionName, method, scope);
629 scriptable.defineProperty(functionName, functionObject, ScriptableObject.EMPTY);
630 }
631 }
632 }
633
634 private static void configureConstants(final ClassConfiguration config, final ScriptableObject scriptable) {
635 final List<ConstantInfo> constants = config.getConstants();
636 if (constants != null) {
637 for (final ConstantInfo constantInfo : constants) {
638 scriptable.defineProperty(constantInfo.getName(), constantInfo.getValue(), constantInfo.getFlag());
639 }
640 }
641 }
642
643 private static void configureProperties(final ClassConfiguration config,
644 final TopLevel scope, final ScriptableObject scriptable) {
645 final Map<String, PropertyInfo> propertyMap = config.getPropertyMap();
646 if (propertyMap != null) {
647 for (final Entry<String, PropertyInfo> propertyEntry : propertyMap.entrySet()) {
648 final PropertyInfo info = propertyEntry.getValue();
649 final Method readMethod = info.getReadMethod();
650 final Method writeMethod = info.getWriteMethod();
651 scriptable.defineProperty(scope, propertyEntry.getKey(), null, readMethod, writeMethod, ScriptableObject.EMPTY);
652 }
653 }
654 }
655
656 private static void configureStaticProperties(final ClassConfiguration config,
657 final TopLevel scope, final ScriptableObject scriptable) {
658 final Map<String, PropertyInfo> staticPropertyMap = config.getStaticPropertyMap();
659 if (staticPropertyMap != null) {
660 for (final Entry<String, ClassConfiguration.PropertyInfo> propertyEntry : staticPropertyMap.entrySet()) {
661 final String propertyName = propertyEntry.getKey();
662 final Method readMethod = propertyEntry.getValue().getReadMethod();
663 final Method writeMethod = propertyEntry.getValue().getWriteMethod();
664 final int flag = ScriptableObject.EMPTY;
665
666 scriptable.defineProperty(scope, propertyName, null, readMethod, writeMethod, flag);
667 }
668 }
669 }
670
671 private static void configureStaticFunctions(final ClassConfiguration config,
672 final TopLevel scope, final ScriptableObject scriptable) {
673 final Map<String, Method> staticFunctionMap = config.getStaticFunctionMap();
674 if (staticFunctionMap != null) {
675 for (final Entry<String, Method> staticFunctionInfo : staticFunctionMap.entrySet()) {
676 final String functionName = staticFunctionInfo.getKey();
677 final Method method = staticFunctionInfo.getValue();
678 final FunctionObject staticFunctionObject = new FunctionObject(functionName, method, scope);
679 scriptable.defineProperty(functionName, staticFunctionObject, ScriptableObject.EMPTY);
680 }
681 }
682 }
683
684 private static void configureSymbolConstants(final ClassConfiguration config, final ScriptableObject scriptable) {
685 final Map<Symbol, String> symbolConstantMap = config.getSymbolConstantMap();
686 if (symbolConstantMap != null) {
687 for (final Entry<Symbol, String> symbolInfo : symbolConstantMap.entrySet()) {
688 scriptable.defineProperty(symbolInfo.getKey(), symbolInfo.getValue(), ScriptableObject.DONTENUM | ScriptableObject.READONLY);
689 }
690 }
691 }
692
693 private static void configureSymbols(final ClassConfiguration config,
694 final TopLevel scope, final ScriptableObject scriptable) {
695 final Map<Symbol, Method> symbolMap = config.getSymbolMap();
696 if (symbolMap != null) {
697 for (final Entry<Symbol, Method> symbolInfo : symbolMap.entrySet()) {
698 final Symbol symbol = symbolInfo.getKey();
699 final Method method = symbolInfo.getValue();
700 final String methodName = method.getName();
701
702 final Callable symbolFunction;
703
704 final Object property = scriptable.get(methodName, scriptable);
705 if (property == Scriptable.NOT_FOUND) {
706 symbolFunction = new FunctionObject(methodName, method, scope);
707 }
708 else {
709 symbolFunction = (Callable) property;
710 }
711 scriptable.defineProperty(symbol, symbolFunction, ScriptableObject.DONTENUM);
712 }
713 }
714 }
715
716
717
718
719
720 @Override
721 public void registerWindowAndMaybeStartEventLoop(final WebWindow webWindow) {
722 if (shutdownPending_) {
723 return;
724 }
725
726 final WebClient webClient = getWebClient();
727 if (webClient != null) {
728 synchronized (javaScriptExecutorLock_) {
729 if (javaScriptExecutor_ == null) {
730 javaScriptExecutor_ = BackgroundJavaScriptFactory.theFactory().createJavaScriptExecutor(webClient);
731 }
732 javaScriptExecutor_.addWindow(webWindow);
733 }
734 }
735 }
736
737
738
739
740 @Override
741 public void prepareShutdown() {
742 shutdownPending_ = true;
743 }
744
745
746
747
748 @Override
749 public void shutdown() {
750 webClient_ = null;
751 contextFactory_ = null;
752 jsConfig_ = null;
753
754 synchronized (javaScriptExecutorLock_) {
755 if (javaScriptExecutor_ != null) {
756 javaScriptExecutor_.shutdown();
757 javaScriptExecutor_ = null;
758 }
759 }
760 if (postponedActions_ != null) {
761 postponedActions_.remove();
762 }
763 if (javaScriptRunning_ != null) {
764 javaScriptRunning_.remove();
765 }
766 if (holdPostponedActions_ != null) {
767 holdPostponedActions_.remove();
768 }
769 }
770
771
772
773
774 @Override
775 public Script compile(final HtmlPage owningPage, final VarScope scope, final String sourceCode,
776 final String sourceName, final int startLine) {
777 WebAssert.notNull("sourceCode", sourceCode);
778
779 if (LOG.isTraceEnabled()) {
780 final String newline = System.lineSeparator();
781 LOG.trace("Javascript compile " + sourceName + newline + sourceCode + newline);
782 }
783
784 final HtmlUnitCompileContextAction action = new HtmlUnitCompileContextAction(owningPage, sourceCode, sourceName, startLine);
785 return (Script) getContextFactory().callSecured(action, owningPage);
786 }
787
788
789
790
791
792
793
794
795
796 public final <T> T callSecured(final ContextAction<T> action, final HtmlPage page) {
797 if (shutdownPending_ || webClient_ == null) {
798
799 return null;
800 }
801
802 return getContextFactory().callSecured(action, page);
803 }
804
805
806
807
808 @Override
809 public Object execute(final HtmlPage page,
810 final VarScope scope,
811 final String sourceCode,
812 final String sourceName,
813 final int startLine) {
814 final Script script = compile(page, scope, sourceCode, sourceName, startLine);
815 if (script == null) {
816
817 return null;
818 }
819 return execute(page, scope, script);
820 }
821
822
823
824
825 @Override
826 public Object execute(final HtmlPage page, final VarScope scope, final Script script) {
827 if (shutdownPending_ || webClient_ == null) {
828
829 return null;
830 }
831 if (page != null && !page.isSandboxAllowed(SANDBOX_ALLOW_SCRIPTS)) {
832
833 return null;
834 }
835
836 final HtmlUnitContextAction action = new HtmlUnitContextAction(page) {
837 @Override
838 public Object doRun(final Context cx) {
839 return script.exec(cx, scope, ScriptableObject.getTopLevelScope(scope).getGlobalThis());
840 }
841
842 @Override
843 protected String getSourceCode(final Context cx) {
844 return null;
845 }
846 };
847
848 return getContextFactory().callSecured(action, page);
849 }
850
851
852
853
854
855
856
857
858
859
860 public Object callFunction(
861 final HtmlPage page,
862 final Function javaScriptFunction,
863 final Scriptable thisObject,
864 final Object[] args,
865 final DomNode node) {
866
867 VarScope scope = ScriptableObject.getTopLevelScope(thisObject.getParentScope());
868
869 if (node != null && node instanceof HtmlElement htmlElement) {
870 final HTMLElement elem = htmlElement.getScriptableObject();
871 scope = new WithScope(scope, elem.getOwnerDocument());
872
873 if (htmlElement instanceof SubmittableElement) {
874 final HtmlForm enclosingForm = htmlElement.getEnclosingForm();
875 if (enclosingForm != null) {
876 scope = new WithScope(scope, enclosingForm.getScriptableObject());
877 }
878 }
879
880 scope = new WithScope(scope, node.getScriptableObject());
881 }
882
883 return callFunction(page, javaScriptFunction, scope, thisObject, args);
884 }
885
886
887
888
889
890
891
892
893
894
895 public Object callFunction(final HtmlPage page, final Function function,
896 final VarScope scope, final Scriptable thisObject, final Object[] args) {
897 if (shutdownPending_ || webClient_ == null) {
898
899 return null;
900 }
901 if (page != null && !page.isSandboxAllowed(SANDBOX_ALLOW_SCRIPTS)) {
902
903 return null;
904 }
905
906 final HtmlUnitContextAction action = new HtmlUnitContextAction(page) {
907 @Override
908 public Object doRun(final Context cx) {
909 if (ScriptRuntime.hasTopCall(cx)) {
910 return function.call(cx, scope, thisObject, args);
911 }
912 return ScriptRuntime.doTopCall(function, cx, scope, thisObject, args, cx.isStrictMode());
913 }
914
915 @Override
916 protected String getSourceCode(final Context cx) {
917 return cx.decompileFunction(function, 2);
918 }
919 };
920 return getContextFactory().callSecured(action, page);
921 }
922
923
924
925
926
927
928
929 @Override
930 public boolean isScriptRunning() {
931 return Boolean.TRUE.equals(javaScriptRunning_.get());
932 }
933
934
935
936
937
938 private final class HtmlUnitCompileContextAction implements ContextAction<Object> {
939 private final HtmlPage page_;
940 private final String sourceCode_;
941 private final String sourceName_;
942 private final int startLine_;
943
944 HtmlUnitCompileContextAction(final HtmlPage page, final String sourceCode, final String sourceName, final int startLine) {
945 page_ = page;
946 sourceCode_ = sourceCode;
947 sourceName_ = sourceName;
948 startLine_ = startLine;
949 }
950
951 @Override
952 public Object run(final Context cx) {
953 try {
954 final Object response;
955 cx.putThreadLocal(KEY_STARTING_PAGE, page_);
956 synchronized (page_) {
957 if (page_ != page_.getEnclosingWindow().getEnclosedPage()) {
958 return null;
959 }
960 response = cx.compileString(sourceCode_, sourceName_, startLine_, null);
961
962 }
963
964 return response;
965 }
966 catch (final Exception e) {
967 handleJavaScriptException(new ScriptException(page_, e, sourceCode_), true);
968 return null;
969 }
970 catch (final TimeoutError e) {
971 handleJavaScriptTimeoutError(page_, e);
972 return null;
973 }
974 }
975 }
976
977
978
979
980
981
982 private abstract class HtmlUnitContextAction implements ContextAction<Object> {
983 private final HtmlPage page_;
984
985 HtmlUnitContextAction(final HtmlPage page) {
986 page_ = page;
987 }
988
989 @Override
990 public final Object run(final Context cx) {
991 final Boolean javaScriptAlreadyRunning = javaScriptRunning_.get();
992 javaScriptRunning_.set(Boolean.TRUE);
993
994
995
996 final Object runningPage = cx.getThreadLocal(KEY_RUNNING_PAGE);
997 cx.putThreadLocal(KEY_RUNNING_PAGE, page_);
998
999 try {
1000 final Object response;
1001 synchronized (page_) {
1002 if (page_ != page_.getEnclosingWindow().getEnclosedPage()) {
1003 return null;
1004 }
1005 response = doRun(cx);
1006 }
1007
1008 cx.processMicrotasks();
1009
1010 if (javaScriptAlreadyRunning == null) {
1011
1012
1013 ContentSecurityPolicy.firePendingViolations();
1014 }
1015
1016
1017
1018 if (!Boolean.TRUE.equals(holdPostponedActions_.get())) {
1019 doProcessPostponedActions();
1020 }
1021
1022 return response;
1023 }
1024 catch (final Exception e) {
1025 handleJavaScriptException(new ScriptException(page_, e, getSourceCode(cx)), true);
1026 return null;
1027 }
1028 catch (final TimeoutError e) {
1029 handleJavaScriptTimeoutError(page_, e);
1030 return null;
1031 }
1032 catch (final PageUnloadedError e) {
1033 if (LOG.isDebugEnabled()) {
1034 LOG.debug("Script stopped because the page '" + page_.getUrl() + "' has been unloaded");
1035 }
1036 return null;
1037 }
1038 finally {
1039 if (javaScriptAlreadyRunning == null) {
1040
1041 ContentSecurityPolicy.firePendingViolations();
1042 }
1043
1044 if (runningPage == null) {
1045 cx.removeThreadLocal(KEY_RUNNING_PAGE);
1046 }
1047 else {
1048 cx.putThreadLocal(KEY_RUNNING_PAGE, runningPage);
1049 }
1050 javaScriptRunning_.set(javaScriptAlreadyRunning);
1051 }
1052 }
1053
1054 protected abstract Object doRun(Context cx);
1055
1056 protected abstract String getSourceCode(Context cx);
1057 }
1058
1059 private void doProcessPostponedActions() {
1060 holdPostponedActions_.remove();
1061
1062 final WebClient webClient = getWebClient();
1063 if (webClient == null) {
1064
1065 postponedActions_.set(null);
1066 return;
1067 }
1068
1069 try {
1070 webClient.loadDownloadedResponses();
1071 }
1072 catch (final RuntimeException e) {
1073 throw e;
1074 }
1075 catch (final Exception e) {
1076 throw new RuntimeException(e);
1077 }
1078
1079 final List<PostponedAction> actions = postponedActions_.get();
1080 if (actions != null && !actions.isEmpty()) {
1081 postponedActions_.set(new ArrayList<>());
1082 try {
1083 for (final PostponedAction action : actions) {
1084 if (LOG.isDebugEnabled()) {
1085 LOG.debug("Processing PostponedAction " + action);
1086 }
1087
1088
1089 if (action.isStillAlive()) {
1090 action.execute();
1091 }
1092 }
1093 }
1094 catch (final RuntimeException e) {
1095 throw e;
1096 }
1097 catch (final Exception e) {
1098 throw JavaScriptEngine.throwAsScriptRuntimeEx(e);
1099 }
1100 }
1101 }
1102
1103
1104
1105
1106
1107 @Override
1108 public void addPostponedAction(final PostponedAction action) {
1109 if (shutdownPending_) {
1110 return;
1111 }
1112
1113 List<PostponedAction> actions = postponedActions_.get();
1114 if (actions == null) {
1115 actions = new ArrayList<>();
1116 postponedActions_.set(actions);
1117 }
1118 actions.add(action);
1119 }
1120
1121
1122
1123
1124
1125
1126 protected void handleJavaScriptException(final ScriptException scriptException, final boolean triggerOnError) {
1127 final WebClient webClient = getWebClient();
1128 if (shutdownPending_ || webClient == null) {
1129
1130 return;
1131 }
1132
1133
1134 final HtmlPage page = scriptException.getPage();
1135 if (triggerOnError && page != null) {
1136 final WebWindow window = page.getEnclosingWindow();
1137 if (window != null) {
1138 final Window w = window.getScriptableObject();
1139 if (w != null) {
1140 try {
1141 w.triggerOnError(scriptException);
1142 }
1143 catch (final Exception e) {
1144 handleJavaScriptException(new ScriptException(page, e, null), false);
1145 }
1146 }
1147 }
1148 }
1149
1150 webClient.getJavaScriptErrorListener().scriptException(page, scriptException);
1151
1152 if (webClient.getOptions().isThrowExceptionOnScriptError()) {
1153 throw scriptException;
1154 }
1155 }
1156
1157
1158
1159
1160
1161
1162 protected void handleJavaScriptTimeoutError(final HtmlPage page, final TimeoutError e) {
1163 final WebClient webClient = getWebClient();
1164 if (shutdownPending_ || webClient == null) {
1165
1166 return;
1167 }
1168
1169 webClient.getJavaScriptErrorListener().timeoutError(page, e.getAllowedTime(), e.getExecutionTime());
1170 if (webClient.getOptions().isThrowExceptionOnScriptError()) {
1171 throw new RuntimeException(e);
1172 }
1173 LOG.info("Caught script timeout error", e);
1174 }
1175
1176
1177
1178
1179
1180 @Override
1181 public void holdPosponedActions() {
1182 holdPostponedActions_.set(Boolean.TRUE);
1183 }
1184
1185
1186
1187
1188
1189 @Override
1190 public void processPostponedActions() {
1191 doProcessPostponedActions();
1192 }
1193
1194
1195
1196
1197 private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
1198 in.defaultReadObject();
1199 initTransientFields();
1200 }
1201
1202 private void initTransientFields() {
1203 javaScriptRunning_ = new ThreadLocal<>();
1204 postponedActions_ = new ThreadLocal<>();
1205 holdPostponedActions_ = new ThreadLocal<>();
1206 shutdownPending_ = false;
1207 }
1208
1209
1210
1211
1212
1213
1214 public Class<? extends HtmlUnitScriptable> getJavaScriptClass(final Class<?> c) {
1215 return jsConfig_.getDomJavaScriptMappingFor(c);
1216 }
1217
1218
1219
1220
1221
1222 @Override
1223 public JavaScriptConfiguration getJavaScriptConfiguration() {
1224 return jsConfig_;
1225 }
1226
1227
1228
1229
1230
1231 @Override
1232 public long getJavaScriptTimeout() {
1233 return getContextFactory().getTimeout();
1234 }
1235
1236
1237
1238
1239
1240 @Override
1241 public void setJavaScriptTimeout(final long timeout) {
1242 getContextFactory().setTimeout(timeout);
1243 }
1244
1245
1246
1247
1248
1249
1250
1251 public static double toNumber(final Object value) {
1252 return ScriptRuntime.toNumber(value);
1253 }
1254
1255
1256
1257
1258
1259
1260
1261 public static String toString(final Object value) {
1262 return ScriptRuntime.toString(value);
1263 }
1264
1265
1266
1267
1268
1269
1270
1271 public static boolean toBoolean(final Object value) {
1272 return ScriptRuntime.toBoolean(value);
1273 }
1274
1275
1276
1277
1278
1279
1280
1281 public static RuntimeException throwAsScriptRuntimeEx(final Throwable e) {
1282 throw Context.throwAsScriptRuntimeEx(e);
1283 }
1284
1285
1286
1287
1288
1289
1290
1291 public static RuntimeException reportRuntimeError(final String message) {
1292 throw Context.reportRuntimeError(message);
1293 }
1294
1295
1296
1297
1298
1299
1300
1301 public static EcmaError syntaxError(final String message) {
1302 return ScriptRuntime.syntaxError(message);
1303 }
1304
1305
1306
1307
1308
1309
1310
1311 public static EcmaError typeError(final String message) {
1312 return ScriptRuntime.typeError(message);
1313 }
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324 public static Scriptable toErrorObject(final EcmaError error, final VarScope scope) {
1325 return ScriptRuntime.wrapException(error, scope, Context.getCurrentContext());
1326 }
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336 public static Scriptable toObject(final VarScope scope, final Object value) {
1337 return ScriptRuntime.toObject(scope, value);
1338 }
1339
1340
1341
1342
1343
1344
1345 public static EcmaError typeErrorIllegalConstructor() {
1346 throw JavaScriptEngine.typeError("Illegal constructor.");
1347 }
1348
1349
1350
1351
1352
1353
1354
1355 public static EcmaError rangeError(final String message) {
1356 return ScriptRuntime.rangeError(message);
1357 }
1358
1359
1360
1361
1362
1363
1364
1365
1366 public static EcmaError constructError(final String error, final String message) {
1367 return ScriptRuntime.constructError(error, message);
1368 }
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380 public static RhinoException asJavaScriptException(final HtmlUnitScriptable scriptable, final String message, final int type) {
1381 final DOMException domException = new DOMException(message, type);
1382 domException.setParentScope(scriptable.getParentScope());
1383
1384 final WindowOrWorkerGlobalScope wow = HtmlUnitScriptable.getWindowOrWorkerGlobalScope(scriptable);
1385 if (wow instanceof Window window) {
1386 domException.setPrototype(window.getPrototype(DOMException.class));
1387 }
1388 else if (wow instanceof WorkerGlobalScope w) {
1389 domException.setPrototype(w.getPrototype(DOMException.class));
1390 }
1391
1392 final EcmaError helper = ScriptRuntime.syntaxError("helper");
1393 String fileName = helper.sourceName();
1394 if (fileName != null) {
1395 fileName = fileName.replaceFirst("script in (.*) from .*", "$1");
1396 }
1397 domException.setLocation(fileName, helper.lineNumber());
1398
1399 return new JavaScriptException(domException, fileName, helper.lineNumber());
1400 }
1401
1402
1403
1404
1405
1406
1407
1408
1409 public static void setFunctionProtoAndParent(final BaseFunction fn, final Context cx, final VarScope scope) {
1410 ScriptRuntime.setFunctionProtoAndParent(fn, cx, scope);
1411 }
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421 public static Scriptable newObject(final VarScope scope, final String constructorName, final Object[] args) {
1422 return ScriptRuntime.newObject(Context.getCurrentContext(), scope, constructorName, args);
1423 }
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434 public static Scriptable newObject(final VarScope scope) {
1435 final NativeObject result = new NativeObject();
1436 ScriptRuntime.setBuiltinProtoAndParent(result, scope, TopLevel.Builtins.Object);
1437 return result;
1438 }
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448 public static Scriptable newArray(final VarScope scope, final int length) {
1449 final NativeArray result = new NativeArray(length);
1450 ScriptRuntime.setBuiltinProtoAndParent(result, scope, TopLevel.Builtins.Array);
1451 return result;
1452 }
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463 public static Scriptable newArrayIteratorTypeKeys(final VarScope scope, final Scriptable arrayLike) {
1464 return new NativeArrayIterator(scope, arrayLike, NativeArrayIterator.ARRAY_ITERATOR_TYPE.KEYS);
1465 }
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476 public static Scriptable newArrayIteratorTypeValues(final VarScope scope, final Scriptable arrayLike) {
1477 return new NativeArrayIterator(scope, arrayLike, NativeArrayIterator.ARRAY_ITERATOR_TYPE.VALUES);
1478 }
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489 public static Scriptable newArrayIteratorTypeEntries(final VarScope scope, final Scriptable arrayLike) {
1490 return new NativeArrayIterator(scope, arrayLike, NativeArrayIterator.ARRAY_ITERATOR_TYPE.ENTRIES);
1491 }
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501 public static Scriptable newArray(final VarScope scope, final Object[] elements) {
1502 if (elements.getClass().getComponentType() != ScriptRuntime.ObjectClass) {
1503 throw new IllegalArgumentException();
1504 }
1505
1506 final NativeArray result = new NativeArray(elements);
1507 ScriptRuntime.setBuiltinProtoAndParent(result, scope, TopLevel.Builtins.Array);
1508 return result;
1509 }
1510
1511
1512
1513
1514
1515
1516
1517
1518 public static NativeUint8Array newUint8Array(final VarScope scope, final byte[] elements) {
1519 final NativeArrayBuffer arrayBuffer = new NativeArrayBuffer(elements.length);
1520 ScriptRuntime.setBuiltinProtoAndParent(arrayBuffer, scope, TopLevel.Builtins.ArrayBuffer);
1521 arrayBuffer.getByteBuffer().put(elements);
1522
1523 final NativeUint8Array uint8Array = new NativeUint8Array(arrayBuffer, 0, elements.length);
1524 ScriptRuntime.setBuiltinProtoAndParent(uint8Array, scope, TopLevel.Builtins.Uint8Array);
1525
1526 return uint8Array;
1527 }
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544 public static boolean iterate(final Context cx, final VarScope scope,
1545 final Scriptable scriptable, final Consumer<Object> consumer) {
1546 if (ScriptableObject.hasProperty(scriptable, SymbolKey.ITERATOR)) {
1547 final Object iterator = ScriptRuntime.callIterator(scriptable, cx, scope);
1548 try (IteratorLikeIterable itr = new IteratorLikeIterable(cx, scope, iterator)) {
1549 for (final Object elem : itr) {
1550 consumer.accept(elem);
1551 }
1552 }
1553
1554 return true;
1555 }
1556
1557 return false;
1558 }
1559
1560
1561
1562
1563
1564
1565
1566 public static int toInt32(final Object o) {
1567 return ScriptRuntime.toInt32(o);
1568 }
1569
1570
1571
1572
1573
1574
1575
1576 public static long toUint32(final Object o) {
1577 return ScriptRuntime.toUint32(o);
1578 }
1579
1580
1581
1582
1583
1584
1585
1586 public static double toInteger(final Object o) {
1587 return ScriptRuntime.toInteger(o);
1588 }
1589
1590
1591
1592
1593
1594
1595
1596
1597 public static double toInteger(final Object[] args, final int index) {
1598 return ScriptRuntime.toInteger(args, index);
1599 }
1600
1601
1602
1603
1604
1605
1606
1607 public static boolean isUndefined(final Object obj) {
1608 return org.htmlunit.corejs.javascript.Undefined.isUndefined(obj);
1609 }
1610
1611
1612
1613
1614
1615
1616
1617 public static boolean isNaN(final Object obj) {
1618 return ScriptRuntime.isNaN(obj);
1619 }
1620
1621
1622
1623
1624
1625
1626
1627 public static boolean isArray(final Object obj) {
1628 return (obj instanceof Scriptable s)
1629 && "Array".equals(s.getClassName());
1630 }
1631
1632
1633
1634
1635
1636
1637
1638 public static boolean isArrayLike(final Scriptable obj) {
1639 return ScriptRuntime.isArrayLike(obj);
1640 }
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655 public static int toArrayLength(final long length) {
1656 if (length < 0) {
1657 throw ScriptRuntime.rangeErrorById("msg.arraylength.bad");
1658 }
1659 if (length > Integer.MAX_VALUE) {
1660 throw ScriptRuntime.rangeErrorById("msg.arraylength.too.big", String.valueOf(length));
1661 }
1662 return (int) length;
1663 }
1664
1665
1666
1667
1668
1669
1670
1671
1672 public static long lengthOfArrayLike(final Context cx, final Scriptable obj) {
1673 return AbstractEcmaObjectOperations.lengthOfArrayLike(cx, obj);
1674 }
1675
1676
1677
1678
1679
1680
1681
1682
1683 public static void iterateArrayLike(final Context cx, final Scriptable arrayLike, final Consumer<Object> consumer) {
1684 final Context context = cx == null ? Context.getCurrentContext() : cx;
1685
1686 final long len = lengthOfArrayLike(context, arrayLike);
1687 for (int i = 0; i < len; i++) {
1688 final Object item = arrayLike.get(i, arrayLike);
1689 consumer.accept(item);
1690 }
1691 }
1692
1693
1694
1695
1696
1697
1698 public static TopLevel getTopCallScope() {
1699 return ScriptRuntime.getTopCallScope(Context.getCurrentContext());
1700 }
1701
1702
1703
1704
1705
1706
1707
1708 public static String uncompressJavaScript(final String scriptSource, final String scriptName) {
1709 final ContextFactory factory = new ContextFactory();
1710 final ContextAction<Object> action = cx -> {
1711 cx.setInterpretedMode(true);
1712 final Script script = cx.compileString(scriptSource, scriptName, 0, null);
1713 return cx.decompileScript(script, 4);
1714 };
1715
1716 return (String) factory.call(action);
1717 }
1718
1719
1720
1721
1722
1723
1724
1725
1726 public static String evaluateProxyAutoConfig(final BrowserVersion browserVersion, final String content, final URL url) {
1727 try (Context cx = Context.enter()) {
1728 final ProxyAutoConfigJavaScriptConfiguration jsConfig =
1729 ProxyAutoConfigJavaScriptConfiguration.getInstance(browserVersion);
1730
1731 final ScriptableObject globalThis = new NativeObject();
1732 final TopLevel scope = cx.initSafeStandardObjects(new TopLevel(globalThis));
1733
1734 for (final ClassConfiguration config : jsConfig.getAll()) {
1735 configureFunctions(config, scope, globalThis);
1736 }
1737
1738 cx.evaluateString(scope, "var ProxyConfig = function() {}; ProxyConfig.bindings = {}; ProxyConfig", "<init>", 1, null);
1739 cx.evaluateString(scope, content, "<Proxy Auto-Config>", 1, null);
1740
1741 final Object[] functionArgs = {url.toExternalForm(), url.getHost()};
1742 final Function f = (Function) scope.get("FindProxyForURL", scope);
1743 final Object result = f.call(cx, scope, globalThis, functionArgs);
1744 return toString(result);
1745 }
1746 }
1747 }