View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
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  * A wrapper for the <a href="http://www.mozilla.org/rhino">Rhino JavaScript engine</a>
101  * that provides browser specific features.
102  *
103  * <p>Like all classes in this package, this class is not intended for direct use
104  * and may change without notice.</p>
105  *
106  * @author Mike Bowler
107  * @author Chen Jun
108  * @author David K. Taylor
109  * @author Chris Erskine
110  * @author Ben Curren
111  * @author David D. Kilzer
112  * @author Marc Guillemot
113  * @author Daniel Gredler
114  * @author Ahmed Ashour
115  * @author Amit Manjhi
116  * @author Ronald Brill
117  * @author Frank Danek
118  * @author Lai Quang Duong
119  * @author Sven Strickroth
120  *
121  * @see <a href="http://groups-beta.google.com/group/netscape.public.mozilla.jseng/browse_thread/thread/b4edac57329cf49f/069e9307ec89111f">
122  *     Rhino and Java Browser</a>
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     /** ScriptRuntime.emptyArgs. */
131     public static final Object[] EMPTY_ARGS = ScriptRuntime.emptyArgs;
132 
133     /** org.htmlunit.corejs.javascript.Undefined.instance. */
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     // per thread like the postponed actions; otherwise e.g. a click() on the main thread holds back the
143     // postponed actions (form submit, navigation...) of a timer running on the JavaScript thread
144     private transient ThreadLocal<Boolean> holdPostponedActions_;
145     // volatile: set by prepareShutdown() while other threads (e.g. the event loop) are still running
146     private transient volatile boolean shutdownPending_;
147 
148     /** The JavaScriptExecutor corresponding to all windows of this Web client. */
149     private transient volatile JavaScriptExecutor javaScriptExecutor_;
150     /** Guards the creation and the shutdown of the {@link #javaScriptExecutor_}. */
151     private final SerializableLock javaScriptExecutorLock_ = new SerializableLock();
152 
153     /**
154      * Key used to place the {@link HtmlPage} for which the JavaScript code is executed
155      * as thread local attribute in current context.
156      */
157     public static final String KEY_STARTING_PAGE = "startingPage";
158 
159     /**
160      * Key used to place the {@link HtmlPage} of the currently running script
161      * as thread local attribute in current context.
162      */
163     static final String KEY_RUNNING_PAGE = "runningPage";
164 
165     /**
166      * Creates an instance for the specified {@link WebClient}.
167      *
168      * @param webClient the client that will own this engine
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      * Returns the web client that this engine is associated with.
185      * @return the web client
186      */
187     private WebClient getWebClient() {
188         return webClient_;
189     }
190 
191     /**
192      * {@inheritDoc}
193      */
194     @Override
195     public HtmlUnitContextFactory getContextFactory() {
196         return contextFactory_;
197     }
198 
199     /**
200      * Performs initialization for the given webWindow.
201      * @param webWindow the web window to initialize for
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); // BUG: null is not useful.
218             }
219             return null;
220         });
221     }
222 
223     /**
224      * Returns the JavaScriptExecutor.
225      * @return the JavaScriptExecutor or null if javascript is disabled
226      *         or no executor was required so far.
227      */
228     public JavaScriptExecutor getJavaScriptExecutor() {
229         return javaScriptExecutor_;
230     }
231 
232     /**
233      * Initializes all the JS stuff for the window.
234      * @param webWindow the web window
235      * @param cx the current context
236      * @throws Exception if something goes wrong
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         // TODO remove the cast
267         URLSearchParams.NativeParamsIterator.init(cx, scope, "URLSearchParams Iterator");
268         FormData.FormDataIterator.init(cx, scope, "FormData Iterator");
269         Headers.HeadersIterator.init(cx, scope);
270 
271         // strange but this is the reality for browsers
272         // because there will be still some sites using this for browser detection the property is
273         // set to null
274         // https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browsers
275         // https://bugzilla.mozilla.org/show_bug.cgi?id=1442035
276         if (browserVersion.hasFeature(JS_WINDOW_INSTALL_TRIGGER_NULL)) {
277             jsWindow.put("InstallTrigger", jsWindow, null);
278         }
279 
280         // special handling for image/option
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      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
299      *
300      * @param scope the scope
301      * @param globalThis the globalThis to set up
302      * @param scopeConfig the {@link ClassConfiguration} that is used for the scope
303      * @param scopeContructorFunctionObject the (already registered) ctor
304      * @param jsConfig the complete jsConfig
305      * @param browserVersion the {@link BrowserVersion}
306      * @param prototypes map of prototypes
307      * @param prototypesPerJSName map of prototypes with the class name as key
308      * @throws Exception in case of error
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             // setup the prototypes
330             if (config == scopeConfig) {
331                 if (extendedClassName == null) {
332                     prototype.setPrototype(objectPrototype);
333                 }
334                 else {
335                     prototype.setPrototype(prototypesPerJSName.get(extendedClassName));
336                 }
337 
338                 // setup constructors
339                 addAsConstructorAndAlias(scopeContructorFunctionObject, scope, globalThis, prototype, config);
340                 configureConstantsStaticPropertiesAndStaticFunctions(config, scope, scopeContructorFunctionObject);
341 
342                 // adjust prototype if needed
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                 // setup constructors
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                             // addAsConstructorAndAlias(..) calls addAsConstructor() from core-js
382                             // addAsConstructor(..) registeres the ctor in the scope already
383                             // therefore we have to remove here
384                             globalThis.delete(prototype.getClassName());
385                         }
386 
387                         // adjust prototype if needed
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             // TODO see issue #1897
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             // TODO see issue #1897
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      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
443      *
444      * @param webClient the WebClient
445      * @param browserVersion the BrowserVersion
446      * @param scope the scope
447      * @param globalThis the window or the DedicatedWorkerGlobalScope
448      */
449     public static void configureRhino(final WebClient webClient, final BrowserVersion browserVersion,
450             final TopLevel scope, final HtmlUnitScriptable globalThis) {
451 
452         // this should be like
453         // NativeConsole.init(scope, globalThis, false, webClient.getWebConsole());
454         // but so far both objects are the same
455         NativeConsole.init(scope, false, webClient.getWebConsole());
456 
457         // https://developer.mozilla.org/en-US/docs/Web/API/console/timeStamp_static
458         // this is not standard and therefore not in Rhino
459         final ScriptableObject console = (ScriptableObject) ScriptableObject.getProperty(globalThis, "console");
460         console.defineFunctionProperties(scope, new String[] {"timeStamp"}, ConsoleCustom.class, ScriptableObject.DONTENUM);
461 
462         // remove some objects, that Rhino defines in top scope but that we don't want
463         deleteProperties(globalThis, "Continuation", "StopIteration", "uneval", "global", "__GeneratorFunction", "SharedArrayBuffer");
464 
465         // Rhino defines too many methods for us, particularly since implementation of ECMAScript5
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         // add Intl
491         Intl.init(scope, globalThis, browserVersion);
492     }
493 
494     /**
495      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
496      *
497      * @param webClient the WebClient
498      * @param browserVersion the BrowserVersion
499      * @param context the current context
500      * @param scope the scope
501      * @param scriptable the window or the DedicatedWorkerGlobalScope
502      * @throws IOException in case of problems
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             // the polyfill installs itself (fetch, Headers, Request and Response) only if there is no fetch()
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             // TODO see issue #1897
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             // TODO see issue #1897
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      * Deletes the properties with the provided names.
548      * @param destination the object from which the properties are to be removed
549      * @param propertiesToDelete the list of property names
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      * Removes prototype properties.
559      * @param scope the scope to search for the prototype
560      * @param className the class for which properties should be removed
561      * @param properties the properties to remove
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      * Configures the specified class for access via JavaScript.
573      * @param config the configuration settings for the class to be configured
574      * @param scope the scope to configure within which to configure the class
575      * @throws InstantiationException if the new class cannot be instantiated
576      * @throws IllegalAccessException if we don't have access to create the new instance
577      * @return the created prototype
578      * @throws Exception in case of errors
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      * Configures constants, static properties and static functions on the object.
595      * @param config the configuration for the object
596      * @param scriptable the object to configure
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      * Configures constants, properties and functions on the object.
607      * @param config the configuration for the object
608      * @param scope the scope
609      * @param scriptable the object to configure
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         // the functions
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                 // a bit strange but this avoid the has call and therefore saves one lookup
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      * Register WebWindow with the JavaScriptExecutor.
718      * @param webWindow the WebWindow to be registered.
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      * {@inheritDoc}
739      */
740     @Override
741     public void prepareShutdown() {
742         shutdownPending_ = true;
743     }
744 
745     /**
746      * Shutdown the JavaScriptEngine.
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      * {@inheritDoc}
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      * Forwards this to the {@link HtmlUnitContextFactory} but with checking shutdown handling.
790      *
791      * @param <T> return type of the action
792      * @param action the contextAction
793      * @param page the page
794      * @return the result of the call
795      */
796     public final <T> T callSecured(final ContextAction<T> action, final HtmlPage page) {
797         if (shutdownPending_ || webClient_ == null) {
798             // shutdown was already called
799             return null;
800         }
801 
802         return getContextFactory().callSecured(action, page);
803     }
804 
805     /**
806      * {@inheritDoc}
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             // happens with syntax error + throwExceptionOnScriptError = false
817             return null;
818         }
819         return execute(page, scope, script);
820     }
821 
822     /**
823      * {@inheritDoc}
824      */
825     @Override
826     public Object execute(final HtmlPage page, final VarScope scope, final Script script) {
827         if (shutdownPending_ || webClient_ == null) {
828             // shutdown was already called
829             return null;
830         }
831         if (page != null && !page.isSandboxAllowed(SANDBOX_ALLOW_SCRIPTS)) {
832             // a sandboxed document without 'allow-scripts' does not execute scripts
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      * Calls a JavaScript function and return the result.
853      * @param page the page
854      * @param javaScriptFunction the function to call
855      * @param thisObject the this object for class method calls
856      * @param args the list of arguments to pass to the function
857      * @param node the HTML element that will act as the context
858      * @return the result of the function call
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      * Calls the given function taking care of synchronization issues.
888      * @param page the interactive page that caused this script to executed
889      * @param function the JavaScript function to execute
890      * @param scope the execution scope
891      * @param thisObject the 'this' object
892      * @param args the function's arguments
893      * @return the function result
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             // shutdown was already called
899             return null;
900         }
901         if (page != null && !page.isSandboxAllowed(SANDBOX_ALLOW_SCRIPTS)) {
902             // a sandboxed document without 'allow-scripts' does not execute scripts (e.g. event handlers)
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      * Indicates if JavaScript is running in current thread.
925      * <p>This allows code to know if their own evaluation has been triggered by some JS code.
926      * </p>
927      * @return {@code true} if JavaScript is running
928      */
929     @Override
930     public boolean isScriptRunning() {
931         return Boolean.TRUE.equals(javaScriptRunning_.get());
932     }
933 
934     /**
935      * Special ContextAction only for compiling. This reduces some code and avoid
936      * some calls.
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_) { // 2 scripts can't be executed in parallel for one page
957                     if (page_ != page_.getEnclosingWindow().getEnclosedPage()) {
958                         return null; // page has been unloaded
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      * Facility for ContextAction usage.
979      * ContextAction should be preferred because according to Rhino doc it
980      * "guarantees proper association of Context instances with the current thread and is faster".
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             // remember the page; the script gets stopped if the page is replaced
995             // by another one (see HtmlUnitContextFactory.observeInstructionCount())
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_) { // 2 scripts can't be executed in parallel for one page
1002                     if (page_ != page_.getEnclosingWindow().getEnclosedPage()) {
1003                         return null; // page has been unloaded
1004                     }
1005                     response = doRun(cx);
1006                 }
1007 
1008                 cx.processMicrotasks();
1009 
1010                 if (javaScriptAlreadyRunning == null) {
1011                     // the outermost script has finished; fire the securitypolicyviolation
1012                     // events before the postponed actions are processed
1013                     ContentSecurityPolicy.firePendingViolations();
1014                 }
1015 
1016                 // doProcessPostponedActions is synchronized
1017                 // moved out of the sync block to avoid deadlocks
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                     // the outermost script has finished (e.g. with an exception)
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             // shutdown was already called
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                     // verify that the page that registered this PostponedAction is still alive
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      * Adds an action that should be executed first when the script currently being executed has finished.
1105      * @param action the action
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      * Handles an exception that occurred during execution of JavaScript code.
1123      * @param scriptException the exception
1124      * @param triggerOnError if true, this triggers the onerror handler
1125      */
1126     protected void handleJavaScriptException(final ScriptException scriptException, final boolean triggerOnError) {
1127         final WebClient webClient = getWebClient();
1128         if (shutdownPending_ || webClient == null) {
1129             // shutdown was already called
1130             return;
1131         }
1132 
1133         // Trigger window.onerror, if it has been set.
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         // Throw a Java exception if the user wants us to.
1152         if (webClient.getOptions().isThrowExceptionOnScriptError()) {
1153             throw scriptException;
1154         }
1155     }
1156 
1157     /**
1158      * Handles an exception that occurred during execution of JavaScript code.
1159      * @param page the page in which the script causing this exception was executed
1160      * @param e the timeout error that was thrown from the script engine
1161      */
1162     protected void handleJavaScriptTimeoutError(final HtmlPage page, final TimeoutError e) {
1163         final WebClient webClient = getWebClient();
1164         if (shutdownPending_ || webClient == null) {
1165             // shutdown was already called
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      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1178      * Indicates that no postponed action should be executed.
1179      */
1180     @Override
1181     public void holdPosponedActions() {
1182         holdPostponedActions_.set(Boolean.TRUE);
1183     }
1184 
1185     /**
1186      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1187      * Process postponed actions, if any.
1188      */
1189     @Override
1190     public void processPostponedActions() {
1191         doProcessPostponedActions();
1192     }
1193 
1194     /**
1195      * Re-initializes transient fields when an object of this type is deserialized.
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      * Gets the class of the JavaScript object for the node class.
1211      * @param c the node class {@link DomNode} or some subclass.
1212      * @return {@code null} if none found
1213      */
1214     public Class<? extends HtmlUnitScriptable> getJavaScriptClass(final Class<?> c) {
1215         return jsConfig_.getDomJavaScriptMappingFor(c);
1216     }
1217 
1218     /**
1219      * Gets the associated configuration.
1220      * @return the configuration
1221      */
1222     @Override
1223     public JavaScriptConfiguration getJavaScriptConfiguration() {
1224         return jsConfig_;
1225     }
1226 
1227     /**
1228      * Returns the javascript timeout.
1229      * @return the javascript timeout
1230      */
1231     @Override
1232     public long getJavaScriptTimeout() {
1233         return getContextFactory().getTimeout();
1234     }
1235 
1236     /**
1237      * Sets the javascript timeout.
1238      * @param timeout the timeout
1239      */
1240     @Override
1241     public void setJavaScriptTimeout(final long timeout) {
1242         getContextFactory().setTimeout(timeout);
1243     }
1244 
1245     /**
1246      * Convert the value to a JavaScript Number value.
1247      *
1248      * @param value a JavaScript value
1249      * @return the corresponding double value converted using the ECMA rules
1250      */
1251     public static double toNumber(final Object value) {
1252         return ScriptRuntime.toNumber(value);
1253     }
1254 
1255     /**
1256      * Convert the value to a JavaScript String value.
1257      *
1258      * @param value a JavaScript value
1259      * @return the corresponding String value converted using the ECMA rules
1260      */
1261     public static String toString(final Object value) {
1262         return ScriptRuntime.toString(value);
1263     }
1264 
1265     /**
1266      * Convert the value to a JavaScript boolean value.
1267      *
1268      * @param value a JavaScript value
1269      * @return the corresponding boolean value converted using the ECMA rules
1270      */
1271     public static boolean toBoolean(final Object value) {
1272         return ScriptRuntime.toBoolean(value);
1273     }
1274 
1275     /**
1276      * Rethrow the exception wrapping it as the script runtime exception.
1277      *
1278      * @param e the exception to rethrow
1279      * @return RuntimeException as dummy the method always throws
1280      */
1281     public static RuntimeException throwAsScriptRuntimeEx(final Throwable e) {
1282         throw Context.throwAsScriptRuntimeEx(e);
1283     }
1284 
1285     /**
1286      * Report a runtime error using the error reporter for the current thread.
1287      *
1288      * @param message the error message to report
1289      * @return RuntimeException as dummy the method always throws
1290      */
1291     public static RuntimeException reportRuntimeError(final String message) {
1292         throw Context.reportRuntimeError(message);
1293     }
1294 
1295     /**
1296      * Report a runtime error using the error reporter for the current thread.
1297      *
1298      * @param message the error message to report
1299      * @return EcmaError
1300      */
1301     public static EcmaError syntaxError(final String message) {
1302         return ScriptRuntime.syntaxError(message);
1303     }
1304 
1305     /**
1306      * Report a runtime error using the error reporter for the current thread.
1307      *
1308      * @param message the error message to report
1309      * @return EcmaError
1310      */
1311     public static EcmaError typeError(final String message) {
1312         return ScriptRuntime.typeError(message);
1313     }
1314 
1315     /**
1316      * Returns the JavaScript error object a script sees when catching the given error
1317      * (e.g. a TypeError for an error created by {@link #typeError(String)}).
1318      * Use this to reject a promise with the error.
1319      *
1320      * @param error the error
1321      * @param scope the scope to create the error object in
1322      * @return the JavaScript error object
1323      */
1324     public static Scriptable toErrorObject(final EcmaError error, final VarScope scope) {
1325         return ScriptRuntime.wrapException(error, scope, Context.getCurrentContext());
1326     }
1327 
1328     /**
1329      * Converts the given value to an object (the abstract operation ToObject); primitives
1330      * are wrapped, {@code null} and {@code undefined} result in a {@code TypeError}.
1331      *
1332      * @param scope the scope to create the wrapper object in
1333      * @param value the value to convert
1334      * @return the object
1335      */
1336     public static Scriptable toObject(final VarScope scope, final Object value) {
1337         return ScriptRuntime.toObject(scope, value);
1338     }
1339 
1340     /**
1341      * Report a TypeError with the message "Illegal constructor.".
1342      *
1343      * @return EcmaError
1344      */
1345     public static EcmaError typeErrorIllegalConstructor() {
1346         throw JavaScriptEngine.typeError("Illegal constructor.");
1347     }
1348 
1349     /**
1350      * Report a runtime error using the error reporter for the current thread.
1351      *
1352      * @param message the error message to report
1353      * @return EcmaError
1354      */
1355     public static EcmaError rangeError(final String message) {
1356         return ScriptRuntime.rangeError(message);
1357     }
1358 
1359     /**
1360      * Constructs a new ECMAScript error.
1361      *
1362      * @param error the error type
1363      * @param message the error message
1364      * @return the constructed {@link EcmaError}
1365      */
1366     public static EcmaError constructError(final String error, final String message) {
1367         return ScriptRuntime.constructError(error, message);
1368     }
1369 
1370     /**
1371      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1372      *
1373      * Creates a {@link DOMException} and encapsulates it into a Rhino-compatible exception.
1374      *
1375      * @param scriptable the scriptable triggering this
1376      * @param message the exception message
1377      * @param type the exception type
1378      * @return the created exception
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      * Todo.
1404      *
1405      * @param fn the function
1406      * @param cx the context
1407      * @param scope the scope
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      * Create a new javascript object by calling the ctor with the provided args.
1415      *
1416      * @param scope the scope to create the object in
1417      * @param constructorName the name of the ctor function to call
1418      * @param args the args
1419      * @return the new object
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      * Create a new JavaScript object.
1427      *
1428      * <p>Equivalent to evaluating "new Object()".
1429      * </p>
1430      *
1431      * @param scope the scope to search for the constructor and to evaluate against
1432      * @return the new object
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      * Create an array with a specified initial length.
1442      *
1443      * @param scope the scope to create the object in
1444      * @param length the initial length (JavaScript arrays may have additional properties added
1445      *     dynamically).
1446      * @return the new array object
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      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1456      *
1457      * Create a new ArrayIterator of type NativeArrayIterator.ARRAY_ITERATOR_TYPE.KEYS
1458      *
1459      * @param scope the scope to create the object in
1460      * @param arrayLike the backend
1461      * @return the new NativeArrayIterator
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      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1469      *
1470      * Create a new ArrayIterator of type NativeArrayIterator.ARRAY_ITERATOR_TYPE.VALUES
1471      *
1472      * @param scope the scope to create the object in
1473      * @param arrayLike the backend
1474      * @return the new NativeArrayIterator
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      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1482      *
1483      * Create a new ArrayIterator of type NativeArrayIterator.ARRAY_ITERATOR_TYPE.ENTRIES
1484      *
1485      * @param scope the scope to create the object in
1486      * @param arrayLike the backend
1487      * @return the new NativeArrayIterator
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      * Create an array with a specified initial length.
1495      *
1496      * @param scope the scope to create the object in
1497      * @param elements the initial elements. Each object in this array must be an acceptable
1498      *     JavaScript type and type of array should be exactly Object[], not SomeObjectSubclass[].
1499      * @return the new array object
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      * Create an Uint8Array with a specified elements.
1513      *
1514      * @param scope the scope to create the object in
1515      * @param elements the initial elements..
1516      * @return the new Uint8Array
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      * Iterates over a JavaScript object using its ES6 iterator property if available,
1531      * invoking the provided consumer action on each element.
1532      *
1533      * <p>If the given {@link Scriptable} defines a {@link SymbolKey#ITERATOR} property,
1534      * this method acquires an iterator via {@link ScriptRuntime#callIterator}, iterates over all
1535      * elements, and passes each element to the {@code consumer}.</p>
1536      *
1537      * @param cx        the current Rhino {@link Context} executing the script
1538      * @param scope     the {@link VarScope} under which evaluation takes place
1539      * @param scriptable the JavaScript object or array to iterate over
1540      * @param consumer  the action to perform on each element yielded by the iterator
1541      * @return {@code true} if the object was iterable and iteration was executed;
1542      *         {@code false} if the object lacks a {@link SymbolKey#ITERATOR} property
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      * Converts the specified value to a 32-bit integer.
1562      *
1563      * @param o the value to convert
1564      * @return the converted 32-bit integer value
1565      */
1566     public static int toInt32(final Object o) {
1567         return ScriptRuntime.toInt32(o);
1568     }
1569 
1570     /**
1571      * Converts the specified value to a long.
1572      *
1573      * @param o the value to convert
1574      * @return the converted long value
1575      */
1576     public static long toUint32(final Object o) {
1577         return ScriptRuntime.toUint32(o);
1578     }
1579 
1580     /**
1581      * Converts the specified value to an integer.
1582      *
1583      * @param o the value to convert
1584      * @return the converted integer value as a {@code double}
1585      */
1586     public static double toInteger(final Object o) {
1587         return ScriptRuntime.toInteger(o);
1588     }
1589 
1590     /**
1591      * Converts the value at the specified array index to an integer.
1592      *
1593      * @param args the array containing the value to convert
1594      * @param index the index of the value in the array
1595      * @return the converted integer value as a {@code double}
1596      */
1597     public static double toInteger(final Object[] args, final int index) {
1598         return ScriptRuntime.toInteger(args, index);
1599     }
1600 
1601     /**
1602      * Determines whether the specified value is {@code undefined}.
1603      *
1604      * @param obj the value to check
1605      * @return {@code true} if the specified value is {@code undefined}
1606      */
1607     public static boolean isUndefined(final Object obj) {
1608         return org.htmlunit.corejs.javascript.Undefined.isUndefined(obj);
1609     }
1610 
1611     /**
1612      * Determines whether the specified value is {@code NaN}.
1613      *
1614      * @param obj the value to check
1615      * @return {@code true} if the specified value is {@code NaN}
1616      */
1617     public static boolean isNaN(final Object obj) {
1618         return ScriptRuntime.isNaN(obj);
1619     }
1620 
1621     /**
1622      * Determines whether the specified value is a JavaScript {@code Array}.
1623      *
1624      * @param obj the value to check
1625      * @return {@code true} if the specified value is a JavaScript {@code Array}
1626      */
1627     public static boolean isArray(final Object obj) {
1628         return (obj instanceof Scriptable s)
1629                     && "Array".equals(s.getClassName());
1630     }
1631 
1632     /**
1633      * Determines whether the specified {@link Scriptable} is array-like.
1634      *
1635      * @param obj the value to check
1636      * @return {@code true} if the specified {@link Scriptable} is array-like
1637      */
1638     public static boolean isArrayLike(final Scriptable obj) {
1639         return ScriptRuntime.isArrayLike(obj);
1640     }
1641 
1642     /**
1643      * Converts the given length to an {@code int} that can be used as the length
1644      * of a Java backed array (or list).
1645      * <p>JavaScript allows array lengths up to 2<sup>32</sup> - 1, but Java arrays are limited
1646      * to {@link Integer#MAX_VALUE} elements; therefore a negative length or a length larger
1647      * than {@link Integer#MAX_VALUE} results in a {@code RangeError}.</p>
1648      *
1649      * @param length the length to convert
1650      * @return the length as {@code int}
1651      * @throws org.htmlunit.corejs.javascript.EcmaError a {@code RangeError} if the length
1652      *         is negative ("Inappropriate array length.") or larger than
1653      *         {@link Integer#MAX_VALUE} ("Array length ... exceeds supported capacity limit.")
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      * Returns the length of the specified array-like {@link Scriptable}.
1667      *
1668      * @param cx the JavaScript context
1669      * @param obj the array-like value
1670      * @return the length of the specified array-like {@link Scriptable}
1671      */
1672     public static long lengthOfArrayLike(final Context cx, final Scriptable obj) {
1673         return AbstractEcmaObjectOperations.lengthOfArrayLike(cx, obj);
1674     }
1675 
1676     /**
1677      * Iterates an arrayLike {@link Scriptable} calling the {@link Consumer} on
1678      * every item.
1679      * @param cx the context or null
1680      * @param arrayLike the {@link Scriptable} to iterate
1681      * @param consumer the {@link Consumer} to call
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      * Returns the top call scope.
1695      *
1696      * @return the top call scope
1697      */
1698     public static TopLevel getTopCallScope() {
1699         return ScriptRuntime.getTopCallScope(Context.getCurrentContext());
1700     }
1701 
1702     /**
1703      * Tries to uncompress the JavaScript code in the provided response.
1704      * @param scriptSource the souce
1705      * @param scriptName the name
1706      * @return the uncompressed JavaScript code
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      * Evaluates the <code>FindProxyForURL</code> method of the specified content.
1721      * @param browserVersion the browser version to use
1722      * @param content the JavaScript content
1723      * @param url the URL to be retrieved
1724      * @return semicolon-separated result
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 }