1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.javascript;
16
17 import static org.htmlunit.BrowserVersionFeatures.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
49
50
51
52
53
54
55
56
57
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
68
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
81 className = getClass().getSuperclass().getSimpleName();
82 }
83 return className;
84 }
85
86
87
88
89
90
91
92 public void setClassName(final String className) {
93 className_ = className;
94 }
95
96
97
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
106 throw JavaScriptEngine.typeError("'set "
107 + name + "' called on an object that does not implement interface " + getClassName());
108 }
109 }
110
111
112
113
114
115
116
117
118 @Override
119 public Object get(final String name, final Scriptable start) {
120
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
130
131
132
133
134
135
136
137
138 protected Object getWithPreemption(final String name) {
139 return NOT_FOUND;
140 }
141
142
143
144
145
146
147
148
149
150
151 protected int getIndexedPropertyCount() {
152 return 0;
153 }
154
155
156
157
158
159
160
161 protected boolean isIndexedPropertyWritable() {
162 return false;
163 }
164
165
166
167
168
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
193
194
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
215
216
217
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
256
257
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
269
270
271
272 public DomNode getDomNodeOrNull() {
273 return domNode_;
274 }
275
276
277
278
279
280 public void setDomNode(final DomNode domNode) {
281 setDomNode(domNode, true);
282 }
283
284
285
286
287
288
289
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
301
302
303
304
305
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
323
324
325
326 public HtmlUnitScriptable makeScriptableFor(final DomNode domNode) {
327
328
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
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
373
374
375
376 @SuppressWarnings("unchecked")
377 public Scriptable getPrototype(final Class<? extends HtmlUnitScriptable> javaScriptClass) {
378
379 HtmlUnitScriptable global = (HtmlUnitScriptable) getWindowOrWorkerGlobalScope(this);
380 if (global == this) {
381
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
393
394
395
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
407
408
409
410 public Window getWindow() throws RuntimeException {
411 return getWindow(this);
412 }
413
414
415
416
417
418
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
447
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
465 if (global != this && global instanceof HtmlUnitScriptable scriptable) {
466 return scriptable.getBrowserVersion();
467 }
468 return null;
469 }
470
471
472
473
474 @Override
475 public boolean hasInstance(final Scriptable instance) {
476 if (getPrototype() == null) {
477
478
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
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
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
530
531
532
533
534
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 }