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.HTMLIMAGE_HTMLELEMENT;
18  import static org.htmlunit.BrowserVersionFeatures.HTMLIMAGE_HTMLUNKNOWNELEMENT;
19  
20  import java.io.IOException;
21  import java.util.ArrayList;
22  import java.util.List;
23  import java.util.function.Supplier;
24  
25  import org.apache.commons.lang3.function.FailableSupplier;
26  import org.apache.commons.logging.Log;
27  import org.apache.commons.logging.LogFactory;
28  import org.htmlunit.BrowserVersion;
29  import org.htmlunit.WebAssert;
30  import org.htmlunit.WebWindow;
31  import org.htmlunit.corejs.javascript.CompoundOperationMap;
32  import org.htmlunit.corejs.javascript.Context;
33  import org.htmlunit.corejs.javascript.JSFunction;
34  import org.htmlunit.corejs.javascript.NativePromise;
35  import org.htmlunit.corejs.javascript.Scriptable;
36  import org.htmlunit.corejs.javascript.ScriptableObject;
37  import org.htmlunit.corejs.javascript.TopLevel;
38  import org.htmlunit.corejs.javascript.VarScope;
39  import org.htmlunit.html.DomNode;
40  import org.htmlunit.html.HtmlImage;
41  import org.htmlunit.javascript.host.Window;
42  import org.htmlunit.javascript.host.WindowOrWorkerGlobalScope;
43  import org.htmlunit.javascript.host.dom.DOMException;
44  import org.htmlunit.javascript.host.html.HTMLElement;
45  import org.htmlunit.javascript.host.html.HTMLUnknownElement;
46  
47  /**
48   * Base class for Rhino host objects in HtmlUnit (not bound to a DOM node).
49   *
50   * @author Mike Bowler
51   * @author David K. Taylor
52   * @author Marc Guillemot
53   * @author Chris Erskine
54   * @author Daniel Gredler
55   * @author Ahmed Ashour
56   * @author Ronald Brill
57   * @author Sven Strickroth
58   */
59  public class HtmlUnitScriptable extends ScriptableObject implements Cloneable {
60  
61      private static final Log LOG = LogFactory.getLog(HtmlUnitScriptable.class);
62  
63      private DomNode domNode_;
64      private String className_;
65  
66      /**
67       * Returns the JavaScript class name.
68       * @return the JavaScript class name
69       */
70      @Override
71      public String getClassName() {
72          if (className_ != null) {
73              return className_;
74          }
75          if (getPrototype() != null) {
76              return getPrototype().getClassName();
77          }
78          String className = getClass().getSimpleName();
79          if (className.isEmpty()) {
80              // for anonymous class
81              className = getClass().getSuperclass().getSimpleName();
82          }
83          return className;
84      }
85  
86      /**
87       * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
88       *
89       * Sets the class name.
90       * @param className the class name.
91       */
92      public void setClassName(final String className) {
93          className_ = className;
94      }
95  
96      /**
97       * {@inheritDoc}
98       */
99      @Override
100     public void put(final String name, final Scriptable start, final Object value) {
101         try {
102             super.put(name, start, value);
103         }
104         catch (final IllegalArgumentException e) {
105             // is it the right place or should Rhino throw a RuntimeError instead of an IllegalArgumentException?
106             throw JavaScriptEngine.typeError("'set "
107                 + name + "' called on an object that does not implement interface " + getClassName());
108         }
109     }
110 
111     /**
112      * Gets a named property from the object.
113      * Normally HtmlUnit objects don't need to overwrite this method as properties are defined
114      * on the prototypes. In some cases where "content" of object
115      * has priority compared to the properties consider using utility {@link #getWithPreemption(String)}.
116      * {@inheritDoc}
117      */
118     @Override
119     public Object get(final String name, final Scriptable start) {
120         // Try to get property configured on object itself.
121         final Object response = super.get(name, start);
122         if (response == NOT_FOUND && this == start) {
123             return getWithPreemption(name);
124         }
125         return response;
126     }
127 
128     /**
129      * <p>Called by {@link #get(String, Scriptable)} to allow retrieval of the property before the prototype
130      * chain is searched.</p>
131      *
132      * <p>IMPORTANT: This method is invoked *very* often by Rhino. If you override this method, the implementation
133      * needs to be as fast as possible!</p>
134      *
135      * @param name the property name
136      * @return {@link Scriptable#NOT_FOUND} if not found
137      */
138     protected Object getWithPreemption(final String name) {
139         return NOT_FOUND;
140     }
141 
142     /**
143      * Returns the number of indexed properties ({@code 0} to {@code count - 1}) this object
144      * exposes as own properties. Host objects supporting indexed properties (e.g. DOMTokenList)
145      * override this; the indexed properties are then listed by Object.keys(),
146      * Object.getOwnPropertyNames(), for...in and have a property descriptor.
147      * The default implementation returns {@code 0}.
148      *
149      * @return the number of indexed own properties
150      */
151     protected int getIndexedPropertyCount() {
152         return 0;
153     }
154 
155     /**
156      * Returns whether the indexed own properties are writable (the object has an indexed setter).
157      * The default implementation returns {@code false}.
158      *
159      * @return true if the indexed properties are writable
160      */
161     protected boolean isIndexedPropertyWritable() {
162         return false;
163     }
164 
165     /**
166      * Overridden to list the indexed properties (see {@link #getIndexedPropertyCount()}) in front
167      * of the other own properties.
168      * {@inheritDoc}
169      */
170     @Override
171     protected Object[] getIds(final CompoundOperationMap<Scriptable> map,
172             final boolean getNonEnumerable, final boolean getSymbols) {
173         final Object[] ids = super.getIds(map, getNonEnumerable, getSymbols);
174         final int count = getIndexedPropertyCount();
175         if (count <= 0) {
176             return ids;
177         }
178 
179         final List<Object> result = new ArrayList<>(count + ids.length);
180         for (int i = 0; i < count; i++) {
181             result.add(Integer.valueOf(i));
182         }
183         for (final Object id : ids) {
184             if (!(id instanceof Integer index && index >= 0 && index < count)) {
185                 result.add(id);
186             }
187         }
188         return result.toArray();
189     }
190 
191     /**
192      * Overridden to provide property descriptors for the indexed properties
193      * (see {@link #getIndexedPropertyCount()}).
194      * {@inheritDoc}
195      */
196     @Override
197     protected DescriptorInfo getOwnPropertyDescriptor(final Context cx, final Object id) {
198         final DescriptorInfo descInfo = super.getOwnPropertyDescriptor(cx, id);
199         if (descInfo != null) {
200             return descInfo;
201         }
202 
203         final int index = toArrayIndex(id);
204         if (index >= 0 && index < getIndexedPropertyCount()) {
205             final Object value = get(index, this);
206             if (value != NOT_FOUND && !JavaScriptEngine.isUndefined(value)) {
207                 return buildDataDescriptor(value, isIndexedPropertyWritable() ? EMPTY : READONLY);
208             }
209         }
210         return null;
211     }
212 
213     /**
214      * Converts the given property id into an array index.
215      *
216      * @param id the property id
217      * @return the index or {@code -1} if the id is not an array index
218      */
219     private static int toArrayIndex(final Object id) {
220         if (id instanceof Integer index) {
221             return index;
222         }
223         if (id instanceof CharSequence seq) {
224             final String str = seq.toString();
225             final int length = str.length();
226             if (length == 0 || length > 9) {
227                 return -1;
228             }
229             if (length > 1 && str.charAt(0) == '0') {
230                 return -1;
231             }
232             int index = 0;
233             for (int i = 0; i < length; i++) {
234                 final char c = str.charAt(i);
235                 if (c < '0' || c > '9') {
236                     return -1;
237                 }
238                 index = index * 10 + (c - '0');
239             }
240             return index;
241         }
242         return -1;
243     }
244 
245     @Override
246     public boolean has(final int index, final Scriptable start) {
247         final Object found = get(index, start);
248         if (Scriptable.NOT_FOUND != found && !JavaScriptEngine.isUndefined(found)) {
249             return true;
250         }
251         return super.has(index, start);
252     }
253 
254     /**
255      * Returns the DOM node that corresponds to this JavaScript object or throw
256      * an exception if one cannot be found.
257      * @return the DOM node
258      */
259     public DomNode getDomNodeOrDie() {
260         if (domNode_ == null) {
261             throw new IllegalStateException("DomNode has not been set for this HtmlUnitScriptable: "
262                         + getClass().getName());
263         }
264         return domNode_;
265     }
266 
267     /**
268      * Returns the DOM node that corresponds to this JavaScript object
269      * or null if a node hasn't been set.
270      * @return the DOM node or null
271      */
272     public DomNode getDomNodeOrNull() {
273         return domNode_;
274     }
275 
276     /**
277      * Sets the DOM node that corresponds to this JavaScript object.
278      * @param domNode the DOM node
279      */
280     public void setDomNode(final DomNode domNode) {
281         setDomNode(domNode, true);
282     }
283 
284     /**
285      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
286      *
287      * Sets the DOM node that corresponds to this JavaScript object.
288      * @param domNode the DOM node
289      * @param assignScriptObject If true, call <code>setScriptObject</code> on domNode
290      */
291     public void setDomNode(final DomNode domNode, final boolean assignScriptObject) {
292         WebAssert.notNull("domNode", domNode);
293         domNode_ = domNode;
294         if (assignScriptObject) {
295             domNode_.setScriptableObject(this);
296         }
297     }
298 
299     /**
300      * Returns the JavaScript object that corresponds to the specified object.
301      * New JavaScript objects will be created as needed. If a JavaScript object
302      * cannot be created for a domNode then NOT_FOUND will be returned.
303      *
304      * @param object a {@link DomNode} or a {@link WebWindow}
305      * @return the JavaScript object or NOT_FOUND
306      */
307     protected HtmlUnitScriptable getScriptableFor(final Object object) {
308         if (object instanceof WebWindow window) {
309             return window.getScriptableObject();
310         }
311 
312         final DomNode domNode = (DomNode) object;
313 
314         final HtmlUnitScriptable scriptObject = domNode.getScriptableObject();
315         if (scriptObject != null) {
316             return scriptObject;
317         }
318         return makeScriptableFor(domNode);
319     }
320 
321     /**
322      * Builds a new the JavaScript object that corresponds to the specified object.
323      * @param domNode the DOM node for which a JS object should be created
324      * @return the JavaScript object
325      */
326     public HtmlUnitScriptable makeScriptableFor(final DomNode domNode) {
327         // Get the JS class name for the specified DOM node.
328         // Walk up the inheritance chain if necessary.
329         Class<? extends HtmlUnitScriptable> javaScriptClass = null;
330         if (domNode instanceof HtmlImage image && "image".equals(image.getOriginalQualifiedName())
331                 && image.wasCreatedByJavascript()) {
332             if (domNode.hasFeature(HTMLIMAGE_HTMLELEMENT)) {
333                 javaScriptClass = HTMLElement.class;
334             }
335             else if (domNode.hasFeature(HTMLIMAGE_HTMLUNKNOWNELEMENT)) {
336                 javaScriptClass = HTMLUnknownElement.class;
337             }
338         }
339         if (javaScriptClass == null) {
340             final JavaScriptEngine javaScriptEngine =
341                     (JavaScriptEngine) getWindow().getWebWindow().getWebClient().getJavaScriptEngine();
342             for (Class<?> c = domNode.getClass(); javaScriptClass == null && c != null; c = c.getSuperclass()) {
343                 javaScriptClass = javaScriptEngine.getJavaScriptClass(c);
344             }
345         }
346 
347         final HtmlUnitScriptable scriptable;
348         if (javaScriptClass == null) {
349             // We don't have a specific subclass for this element so create something generic.
350             scriptable = new HTMLElement();
351             if (LOG.isDebugEnabled()) {
352                 LOG.debug("No JavaScript class found for element <" + domNode.getNodeName() + ">. Using HTMLElement");
353             }
354         }
355         else {
356             try {
357                 scriptable = javaScriptClass.getDeclaredConstructor().newInstance();
358             }
359             catch (final Exception e) {
360                 throw JavaScriptEngine.throwAsScriptRuntimeEx(e);
361             }
362         }
363 
364         scriptable.setParentScope(getParentScope());
365         scriptable.setPrototype(getPrototype(javaScriptClass));
366         scriptable.setDomNode(domNode);
367 
368         return scriptable;
369     }
370 
371     /**
372      * Gets the prototype object for the given host class.
373      * @param javaScriptClass the host class
374      * @return the prototype
375      */
376     @SuppressWarnings("unchecked")
377     public Scriptable getPrototype(final Class<? extends HtmlUnitScriptable> javaScriptClass) {
378         // the window or the worker global scope; both override this method
379         HtmlUnitScriptable global = (HtmlUnitScriptable) getWindowOrWorkerGlobalScope(this);
380         if (global == this) {
381             // e.g. the prototype of the WorkerGlobalScope
382             global = getWindow();
383         }
384         final Scriptable prototype = global.getPrototype(javaScriptClass);
385         if (prototype == null && javaScriptClass != HtmlUnitScriptable.class) {
386             return getPrototype((Class<? extends HtmlUnitScriptable>) javaScriptClass.getSuperclass());
387         }
388         return prototype;
389     }
390 
391     /**
392      * Returns the JavaScript default value of this object. This is the JavaScript equivalent of a toString() in Java.
393      *
394      * @param hint a hint as to the format of the default value (ignored in this case)
395      * @return the default value
396      */
397     @Override
398     public Object getDefaultValue(final Class<?> hint) {
399         if (String.class.equals(hint) || hint == null) {
400             return "[object " + getClassName() + "]";
401         }
402         return super.getDefaultValue(hint);
403     }
404 
405     /**
406      * Gets the window that is the top scope for this object.
407      * @return the window associated with this object
408      * @throws RuntimeException if the window cannot be found, which should never occur
409      */
410     public Window getWindow() throws RuntimeException {
411         return getWindow(this);
412     }
413 
414     /**
415      * Gets the window that is the top scope for the specified object.
416      * @param s the JavaScript object whose associated window is to be returned
417      * @return the window associated with the specified JavaScript object
418      * @throws RuntimeException if the window cannot be found, which should never occur
419      */
420     protected static Window getWindow(final Scriptable s) throws RuntimeException {
421         if (s instanceof Window window) {
422             return window;
423         }
424 
425         final TopLevel topLevel = ScriptableObject.getTopLevelScope(s.getParentScope());
426         if (topLevel.getGlobalThis() instanceof Window window) {
427             return window;
428         }
429         throw new RuntimeException("Unable to find window associated with " + s);
430     }
431 
432     protected static WindowOrWorkerGlobalScope getWindowOrWorkerGlobalScope(
433                         final Scriptable s) throws RuntimeException {
434         if (s instanceof WindowOrWorkerGlobalScope wow) {
435             return wow;
436         }
437 
438         final TopLevel topLevel = ScriptableObject.getTopLevelScope(s.getParentScope());
439         if (topLevel.getGlobalThis() instanceof WindowOrWorkerGlobalScope wow) {
440             return wow;
441         }
442         throw new RuntimeException("Unable to find WindowOrWorkerGlobalScope associated with " + s);
443     }
444 
445     /**
446      * Gets the browser version currently used.
447      * @return the browser version
448      */
449     public BrowserVersion getBrowserVersion() {
450         final DomNode node = getDomNodeOrNull();
451         if (node != null) {
452             return node.getPage().getWebClient().getBrowserVersion();
453         }
454 
455         final WindowOrWorkerGlobalScope global = getWindowOrWorkerGlobalScope(this);
456         if (global instanceof Window window) {
457             final WebWindow webWindow = window.getWebWindow();
458             if (webWindow != null) {
459                 return webWindow.getWebClient().getBrowserVersion();
460             }
461             return null;
462         }
463 
464         // e.g. the worker global scope
465         if (global != this && global instanceof HtmlUnitScriptable scriptable) {
466             return scriptable.getBrowserVersion();
467         }
468         return null;
469     }
470 
471     /**
472      * {@inheritDoc}
473      */
474     @Override
475     public boolean hasInstance(final Scriptable instance) {
476         if (getPrototype() == null) {
477             // to handle cases like "x instanceof HTMLElement",
478             // but HTMLElement is not in the prototype chain of any element
479             final Object prototype = get("prototype", this);
480             if (!(prototype instanceof ScriptableObject)) {
481                 throw JavaScriptEngine.throwAsScriptRuntimeEx(new Exception("Null prototype"));
482             }
483             return ((ScriptableObject) prototype).hasInstance(instance);
484         }
485 
486         return super.hasInstance(instance);
487     }
488 
489     /**
490      * {@inheritDoc}
491      */
492     @Override
493     protected Object equivalentValues(final Object value) {
494         if (value instanceof HtmlUnitScriptableProxy<?> proxy) {
495             return super.equivalentValues(proxy.getDelegee());
496         }
497         return super.equivalentValues(value);
498     }
499 
500     /**
501      * {@inheritDoc}
502      */
503     @Override
504     public HtmlUnitScriptable clone() {
505         try {
506             return (HtmlUnitScriptable) super.clone();
507         }
508         catch (final Exception e) {
509             throw new IllegalStateException("Clone not supported");
510         }
511     }
512 
513     protected NativePromise setupPromise(final FailableSupplier<Object, IOException> resolver) {
514         final VarScope scope = ScriptableObject.getTopLevelScope(getParentScope());
515         final JSFunction ctor = (JSFunction) getProperty(scope, "Promise");
516 
517         try {
518             final JSFunction resolve = (JSFunction) getProperty(ctor, "resolve");
519             return (NativePromise) resolve.call(Context.getCurrentContext(), scope,
520                                                 ctor, new Object[] {resolver.get()});
521         }
522         catch (final IOException e) {
523             final JSFunction reject = (JSFunction) getProperty(ctor, "reject");
524             return (NativePromise) reject.call(Context.getCurrentContext(), scope, ctor, new Object[] {e.getMessage()});
525         }
526     }
527 
528     /**
529      * Creates a {@link DOMException} with proper parent scope and prototype initialized.
530      * This ensures JavaScript getters (such as {@code name}) are correctly resolved in Rhino.
531      *
532      * @param message the exception message
533      * @param errorCode the error code (e.g., {@link DOMException#SYNTAX_ERR})
534      * @return the initialized {@link DOMException} host object
535      */
536     protected DOMException createDOMException(final String message, final int errorCode) {
537         final DOMException domException = new DOMException(message, errorCode);
538         domException.setParentScope(getParentScope());
539         domException.setPrototype(ScriptableObject.getClassPrototype(getParentScope(), domException.getClassName()));
540         return domException;
541     }
542 
543     protected NativePromise setupRejectedPromise(final Supplier<Object> resolver) {
544         final VarScope scope = ScriptableObject.getTopLevelScope(getParentScope());
545         final JSFunction ctor = (JSFunction) getProperty(scope, "Promise");
546         final JSFunction reject = (JSFunction) getProperty(ctor, "reject");
547         return (NativePromise) reject.call(Context.getCurrentContext(), scope, ctor, new Object[] {resolver.get()});
548     }
549 }