net.sourceforge.htmlunit.corejs.javascript.ScriptableObject Java Examples
The following examples show how to use
net.sourceforge.htmlunit.corejs.javascript.ScriptableObject.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Event.java From htmlunit with Apache License 2.0 | 6 votes |
/** * JavaScript constructor. * * @param type the event type * @param details the event details (optional) */ @JsxConstructor({CHROME, FF, FF68, FF60}) public void jsConstructor(final String type, final ScriptableObject details) { boolean bubbles = false; boolean cancelable = false; if (details != null && !Undefined.isUndefined(details)) { final Boolean detailBubbles = (Boolean) details.get("bubbles"); if (detailBubbles != null) { bubbles = detailBubbles.booleanValue(); } final Boolean detailCancelable = (Boolean) details.get("cancelable"); if (detailCancelable != null) { cancelable = detailCancelable.booleanValue(); } } initEvent(type, bubbles, cancelable); }
Example #2
Source File: Range.java From HtmlUnit-Android with Apache License 2.0 | 6 votes |
/** * Returns an object that bounds the contents of the range. * this a rectangle enclosing the union of the bounding rectangles for all the elements in the range. * @return an object the bounds the contents of the range */ @JsxFunction public ClientRect getBoundingClientRect() { final ClientRect rect = new ClientRect(); rect.setParentScope(getWindow()); rect.setPrototype(getPrototype(rect.getClass())); // simple impl for now for (DomNode node : toW3C().containedNodes()) { final ScriptableObject scriptable = node.getScriptableObject(); if (scriptable instanceof HTMLElement) { final ClientRect childRect = ((HTMLElement) scriptable).getBoundingClientRect(); rect.setTop(Math.min(rect.getTop(), childRect.getTop())); rect.setLeft(Math.min(rect.getLeft(), childRect.getLeft())); rect.setRight(Math.max(rect.getRight(), childRect.getRight())); rect.setBottom(Math.max(rect.getBottom(), childRect.getBottom())); } } return rect; }
Example #3
Source File: HTMLFormElement.java From HtmlUnit-Android with Apache License 2.0 | 6 votes |
/** * {@inheritDoc} */ @Override public Object call(final Context cx, final Scriptable scope, final Scriptable thisObj, final Object[] args) { if (!getBrowserVersion().hasFeature(JS_FORM_USABLE_AS_FUNCTION)) { throw Context.reportRuntimeError("Not a function."); } if (args.length > 0) { final Object arg = args[0]; if (arg instanceof String) { return ScriptableObject.getProperty(this, (String) arg); } else if (arg instanceof Number) { return ScriptableObject.getProperty(this, ((Number) arg).intValue()); } } return Undefined.instance; }
Example #4
Source File: Range.java From htmlunit with Apache License 2.0 | 6 votes |
/** * Retrieves a collection of rectangles that describes the layout of the contents of an object * or range within the client. Each rectangle describes a single line. * @return a collection of rectangles that describes the layout of the contents */ @JsxFunction public ClientRectList getClientRects() { final Window w = getWindow(); final ClientRectList rectList = new ClientRectList(); rectList.setParentScope(w); rectList.setPrototype(getPrototype(rectList.getClass())); // simple impl for now for (DomNode node : toW3C().containedNodes()) { final ScriptableObject scriptable = node.getScriptableObject(); if (scriptable instanceof HTMLElement) { final ClientRect rect = new ClientRect(0, 0, 1, 1); rect.setParentScope(w); rect.setPrototype(getPrototype(rect.getClass())); rectList.add(rect); } } return rectList; }
Example #5
Source File: Document.java From htmlunit with Apache License 2.0 | 6 votes |
private static org.w3c.dom.traversal.NodeFilter createFilterWrapper(final Scriptable filter, final boolean filterFunctionOnly) { org.w3c.dom.traversal.NodeFilter filterWrapper = null; if (filter != null) { filterWrapper = new org.w3c.dom.traversal.NodeFilter() { @Override public short acceptNode(final org.w3c.dom.Node n) { final Object[] args = new Object[] {((DomNode) n).getScriptableObject()}; final Object response; if (filter instanceof Callable) { response = ((Callable) filter).call(Context.getCurrentContext(), filter, filter, args); } else { if (filterFunctionOnly) { throw Context.reportRuntimeError("only a function is allowed as filter"); } response = ScriptableObject.callMethod(filter, "acceptNode", args); } return (short) Context.toNumber(response); } }; } return filterWrapper; }
Example #6
Source File: AbstractList.java From htmlunit with Apache License 2.0 | 6 votes |
/** * Creates an instance. * * @param domNode the {@link DomNode} * @param attributeChangeSensitive indicates if the content of the collection may change when an attribute * of a descendant node of parentScope changes (attribute added, modified or removed) * @param initialElements the initial content for the cache */ private AbstractList(final DomNode domNode, final boolean attributeChangeSensitive, final List<DomNode> initialElements) { if (domNode != null) { setDomNode(domNode, false); final ScriptableObject parentScope = domNode.getScriptableObject(); if (parentScope != null) { setParentScope(parentScope); setPrototype(getPrototype(getClass())); } } attributeChangeSensitive_ = attributeChangeSensitive; cachedElements_ = initialElements; if (initialElements != null) { registerListener(); } }
Example #7
Source File: HtmlUnitScriptable.java From HtmlUnit-Android with Apache License 2.0 | 6 votes |
/** * {@inheritDoc} * Same as base implementation, but includes all methods inherited from super classes as well. */ @Override public void defineProperty(final String propertyName, final Class<?> clazz, int attributes) { final int length = propertyName.length(); if (length == 0) { throw new IllegalArgumentException(); } final char[] buf = new char[3 + length]; propertyName.getChars(0, length, buf, 3); buf[3] = Character.toUpperCase(buf[3]); buf[0] = 'g'; buf[1] = 'e'; buf[2] = 't'; final String getterName = new String(buf); buf[0] = 's'; final String setterName = new String(buf); final Method[] methods = clazz.getMethods(); final Method getter = findMethod(methods, getterName); final Method setter = findMethod(methods, setterName); if (setter == null) { attributes |= ScriptableObject.READONLY; } defineProperty(propertyName, null, getter, setter, attributes); }
Example #8
Source File: HtmlUnitScriptable.java From htmlunit with Apache License 2.0 | 6 votes |
/** * {@inheritDoc} * Same as base implementation, but includes all methods inherited from super classes as well. */ @Override public void defineProperty(final String propertyName, final Class<?> clazz, int attributes) { final int length = propertyName.length(); if (length == 0) { throw new IllegalArgumentException(); } final char[] buf = new char[3 + length]; propertyName.getChars(0, length, buf, 3); buf[3] = Character.toUpperCase(buf[3]); buf[0] = 'g'; buf[1] = 'e'; buf[2] = 't'; final String getterName = new String(buf); buf[0] = 's'; final String setterName = new String(buf); final Method[] methods = clazz.getMethods(); final Method getter = findMethod(methods, getterName); final Method setter = findMethod(methods, setterName); if (setter == null) { attributes |= ScriptableObject.READONLY; } defineProperty(propertyName, null, getter, setter, attributes); }
Example #9
Source File: HtmlPage.java From htmlunit with Apache License 2.0 | 6 votes |
private String getAttributeValue(final DomElement element, final String attribute) { // first try real attributes String value = element.getAttribute(attribute); if (DomElement.ATTRIBUTE_NOT_DEFINED == value && getWebClient().isJavaScriptEngineEnabled() && !(element instanceof HtmlApplet) && !(element instanceof HtmlObject)) { // second try are JavaScript attributes // ...but applets/objects are a bit special so ignore them final Object o = element.getScriptableObject(); if (o instanceof ScriptableObject) { final ScriptableObject scriptObject = (ScriptableObject) o; // we have to make sure the scriptObject has a slot for the given attribute. // just using get() may use e.g. getWithPreemption(). if (scriptObject.has(attribute, scriptObject)) { final Object jsValue = scriptObject.get(attribute, scriptObject); if (jsValue != Scriptable.NOT_FOUND && jsValue instanceof String) { value = (String) jsValue; } } } } return value; }
Example #10
Source File: MSXMLJavaScriptEnvironment.java From htmlunit with Apache License 2.0 | 6 votes |
/** * Configures constants, properties and functions on the object. * @param config the configuration for the object * @param scriptable the object to configure */ private static void configureConstantsPropertiesAndFunctions(final ClassConfiguration config, final ScriptableObject scriptable) { // the constants configureConstants(config, scriptable); // the properties final Map<String, PropertyInfo> propertyMap = config.getPropertyMap(); for (final Map.Entry<String, PropertyInfo> entry : propertyMap.entrySet()) { final PropertyInfo info = entry.getValue(); final Method readMethod = info.getReadMethod(); final Method writeMethod = info.getWriteMethod(); scriptable.defineProperty(entry.getKey(), null, readMethod, writeMethod, ScriptableObject.EMPTY); } final int attributes = ScriptableObject.DONTENUM; // the functions for (final Entry<String, Method> functionInfo : config.getFunctionEntries()) { final String functionName = functionInfo.getKey(); final Method method = functionInfo.getValue(); final FunctionObject functionObject = new FunctionObject(functionName, method, scriptable); scriptable.defineProperty(functionName, functionObject, attributes); } }
Example #11
Source File: Event.java From HtmlUnit-Android with Apache License 2.0 | 6 votes |
/** * JavaScript constructor. * * @param type the event type * @param details the event details (optional) */ @JsxConstructor({CHROME, FF, EDGE}) public void jsConstructor(final String type, final ScriptableObject details) { boolean bubbles = false; boolean cancelable = false; if (details != null && details != Undefined.instance) { final Boolean detailBubbles = (Boolean) details.get("bubbles"); if (detailBubbles != null) { bubbles = detailBubbles.booleanValue(); } final Boolean detailCancelable = (Boolean) details.get("cancelable"); if (detailCancelable != null) { cancelable = detailCancelable.booleanValue(); } } initEvent(type, bubbles, cancelable); }
Example #12
Source File: Symbol.java From HtmlUnit-Android with Apache License 2.0 | 6 votes |
/** * Searches for existing symbols in a runtime-wide symbol registry with the given key and returns it if found. * Otherwise a new symbol gets created in the global symbol registry with this key. * @param context the context * @param thisObj this object * @param args the arguments * @param function the function * @return the symbol */ @JsxStaticFunction(functionName = "for") public static Symbol forFunction(final Context context, final Scriptable thisObj, final Object[] args, final Function function) { final String key = Context.toString(args.length != 0 ? args[0] : Undefined.instance); Symbol symbol = (Symbol) ((ScriptableObject) thisObj).get(key); if (symbol == null) { final SimpleScriptable parentScope = (SimpleScriptable) thisObj.getParentScope(); symbol = new Symbol(); symbol.name_ = key; symbol.setParentScope(parentScope); symbol.setPrototype(parentScope.getPrototype(symbol.getClass())); thisObj.put(key, thisObj, symbol); } return symbol; }
Example #13
Source File: JSObject.java From htmlunit with Apache License 2.0 | 6 votes |
/** * Evaluates a JavaScript expression. * The expression is a string of JavaScript source code which will be evaluated in the context given by "this". * * @param expression the JavaScript expression * @return result Object * @throws JSException in case or error */ public Object eval(final String expression) throws JSException { if (LOG.isInfoEnabled()) { LOG.info("JSObject eval '" + expression + "'"); } final Page page = Window_.getWebWindow().getEnclosedPage(); if (page instanceof HtmlPage) { final HtmlPage htmlPage = (HtmlPage) page; final ScriptResult result = htmlPage.executeJavaScript(expression); final Object jsResult = result.getJavaScriptResult(); if (jsResult instanceof ScriptableObject) { return new JSObject((ScriptableObject) jsResult); } if (jsResult instanceof ConsString) { return ((ConsString) jsResult).toString(); } return jsResult; } return null; }
Example #14
Source File: FileReader.java From htmlunit with Apache License 2.0 | 6 votes |
/** * Reads the contents of the specified {@link Blob} or {@link File}. * @param object the {@link Blob} or {@link File} from which to read * @throws IOException if an error occurs */ @JsxFunction public void readAsArrayBuffer(final Object object) throws IOException { readyState_ = LOADING; final java.io.File file = ((File) object).getFile(); try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) { FileUtils.copyFile(file, bos); final byte[] bytes = bos.toByteArray(); final NativeArrayBuffer buffer = new NativeArrayBuffer(bytes.length); System.arraycopy(bytes, 0, buffer.getBuffer(), 0, bytes.length); buffer.setParentScope(getParentScope()); buffer.setPrototype(ScriptableObject.getClassPrototype(getWindow(), buffer.getClassName())); result_ = buffer; } readyState_ = DONE; final Event event = new Event(this, Event.TYPE_LOAD); fireEvent(event); }
Example #15
Source File: HTMLOptionsCollection.java From HtmlUnit-Android with Apache License 2.0 | 6 votes |
/** * <p>If IE is emulated, and this class does not have the specified property, and the owning * select *does* have the specified property, this method delegates the call to the parent * select element.</p> * * @param name {@inheritDoc} * @param start {@inheritDoc} * @param value {@inheritDoc} */ @Override public void put(final String name, final Scriptable start, final Object value) { if (htmlSelect_ == null) { // This object hasn't been initialized; it's probably being used as a prototype. // Just pretend we didn't even see this invocation and let Rhino handle it. super.put(name, start, value); return; } final HTMLSelectElement parent = (HTMLSelectElement) htmlSelect_.getScriptableObject(); if (!has(name, start) && ScriptableObject.hasProperty(parent, name)) { ScriptableObject.putProperty(parent, name, value); } else { super.put(name, start, value); } }
Example #16
Source File: PointerEvent.java From HtmlUnit-Android with Apache License 2.0 | 6 votes |
private static Object getValue(final ScriptableObject object, final String name, final Object defaulValue) { Object value = object.get(name); if (value != null) { if (defaulValue instanceof String) { value = String.valueOf(value); } else if (defaulValue instanceof Double) { value = (double) Context.toNumber(value); } else if (defaulValue instanceof Number) { value = (int) Context.toNumber(value); } else { value = Context.toBoolean(value); } } else { value = defaulValue; } return value; }
Example #17
Source File: HtmlUnitRegExpProxy2Test.java From htmlunit with Apache License 2.0 | 6 votes |
/** * Test if the custom fix is needed or not. When this test fails, then it means that the problem is solved in * Rhino and that custom fix for String.match in {@link HtmlUnitRegExpProxy} is not needed anymore (and that * this test can be removed, or turned positive). * @throws Exception if the test fails */ @Test public void matchFixNeeded() throws Exception { final WebClient client = getWebClient(); final ContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory(); final Context cx = cf.enterContext(); try { final ScriptableObject topScope = cx.initStandardObjects(); cx.evaluateString(topScope, scriptTestMatch_, "test script String.match", 0, null); try { cx.evaluateString(topScope, scriptTestMatch_, "test script String.match", 0, null); } catch (final JavaScriptException e) { assertTrue(e.getMessage().indexOf("Expected >") == 0); } } finally { Context.exit(); } }
Example #18
Source File: ClassConfiguration.java From HtmlUnit-Android with Apache License 2.0 | 6 votes |
/** * Add the constant to the configuration. * @param name - Name of the configuration */ public void addConstant(final String name) { try { final Object value = getHostClass().getField(name).get(null); int flag = ScriptableObject.READONLY | ScriptableObject.PERMANENT; // https://code.google.com/p/chromium/issues/detail?id=500633 if (getClassName().endsWith("Array")) { flag |= ScriptableObject.DONTENUM; } constants_.add(new ConstantInfo(name, value, flag)); } catch (final Exception e) { throw Context.reportRuntimeError("Cannot get field '" + name + "' for type: " + getHostClass().getName()); } }
Example #19
Source File: ObjectCustom.java From HtmlUnit-Android with Apache License 2.0 | 6 votes |
/** * Returns an array of all symbol properties found directly upon a given object. * @param context the JavaScript context * @param thisObj the scriptable * @param args the arguments passed into the method * @param function the function * @return array */ public static Scriptable getOwnPropertySymbols( final Context context, final Scriptable thisObj, final Object[] args, final Function function) { if (args.length == 0) { throw ScriptRuntime.typeError("Cannot convert undefined or null to object"); } if (!(args[0] instanceof ScriptableObject)) { throw ScriptRuntime.typeError("Cannot convert " + Context.toString(args[0]) + " to object"); } final ScriptableObject o = (ScriptableObject) args[0]; final List<Object> list = new ArrayList<>(); for (final Object id : o.getAllIds()) { if (id.toString().startsWith("Symbol(")) { list.add(id); } } return context.newArray(thisObj, list.toArray(new Object[list.size()])); }
Example #20
Source File: Document.java From HtmlUnit-Android with Apache License 2.0 | 5 votes |
/** * Returns the value of the {@code frames} property. * @see <a href="http://msdn.microsoft.com/en-us/library/ms537459.aspx">MSDN documentation</a> * @return the live collection of frames contained by this document */ @JsxGetter(IE) public Object getFrames() { if (ScriptableObject.getTopLevelScope(this) == null) { throw ScriptRuntime.constructError("Error", "Not implemented"); } return getWindow().getFrames_js(); }
Example #21
Source File: PopStateEvent.java From HtmlUnit-Android with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ @Override @JsxConstructor({CHROME, FF, EDGE}) public void jsConstructor(final String type, final ScriptableObject details) { super.jsConstructor(type, details); if (details != null && details != Undefined.instance) { state_ = details.get("state"); } }
Example #22
Source File: HTMLDocument.java From HtmlUnit-Android with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ @Override @JsxFunction(FF) public void close() throws IOException { if (writeInCurrentDocument_) { LOG.warn("close() called when document is not open."); } else { final HtmlPage page = getPage(); final URL url = page.getUrl(); final StringWebResponse webResponse = new StringWebResponse(writeBuilder_.toString(), url); webResponse.setFromJavascript(true); writeInCurrentDocument_ = true; writeBuilder_.setLength(0); final WebClient webClient = page.getWebClient(); final WebWindow window = page.getEnclosingWindow(); // reset isAttachedToPageDuringOnload_ to trigger the onload event for chrome also if (window instanceof FrameWindow) { final BaseFrameElement frame = ((FrameWindow) window).getFrameElement(); final ScriptableObject scriptable = frame.getScriptableObject(); if (scriptable instanceof HTMLIFrameElement) { ((HTMLIFrameElement) scriptable).onRefresh(); } } webClient.loadWebResponseInto(webResponse, window); } }
Example #23
Source File: JavaScriptEngine.java From htmlunit with Apache License 2.0 | 5 votes |
/** * Configures constants, properties and functions on the object. * @param config the configuration for the object * @param scriptable the object to configure */ private static void configureConstantsPropertiesAndFunctions(final ClassConfiguration config, final ScriptableObject scriptable) { configureConstants(config, scriptable); configureProperties(config, scriptable); configureFunctions(config, scriptable); }
Example #24
Source File: RecursiveFunctionObject.java From HtmlUnit-Android with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ @Override public Object get(final String name, final Scriptable start) { final String superFunctionName = super.getFunctionName(); if ("prototype".equals(name)) { switch (superFunctionName) { case "CSS": case "Proxy": return NOT_FOUND; default: } } Object value = super.get(name, start); if (value == NOT_FOUND && !"Image".equals(superFunctionName) && !"Option".equals(superFunctionName) && (!"WebGLContextEvent".equals(superFunctionName) || getBrowserVersion().hasFeature(JS_WEBGL_CONTEXT_EVENT_CONSTANTS))) { Class<?> klass = getPrototypeProperty().getClass(); final BrowserVersion browserVersion = getBrowserVersion(); while (value == NOT_FOUND && HtmlUnitScriptable.class.isAssignableFrom(klass)) { final ClassConfiguration config = AbstractJavaScriptConfiguration.getClassConfiguration( klass.asSubclass(HtmlUnitScriptable.class), browserVersion); if (config != null) { for (final ConstantInfo constantInfo : config.getConstants()) { if (constantInfo.getName().equals(name)) { value = ScriptableObject.getProperty((Scriptable) getPrototypeProperty(), name); break; } } } klass = klass.getSuperclass(); } } return value; }
Example #25
Source File: JavaScriptEngine.java From HtmlUnit-Android with Apache License 2.0 | 5 votes |
private static void configureStaticFunctions(final ClassConfiguration config, final ScriptableObject scriptable) { for (final Entry<String, Method> staticfunctionInfo : config.getStaticFunctionEntries()) { final String functionName = staticfunctionInfo.getKey(); final Method method = staticfunctionInfo.getValue(); final FunctionObject staticFunctionObject = new FunctionObject(functionName, method, scriptable); scriptable.defineProperty(functionName, staticFunctionObject, ScriptableObject.EMPTY); } }
Example #26
Source File: DOMStringMap.java From HtmlUnit-Android with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ @Override public void put(final String name, final Scriptable start, final Object value) { if (!(ScriptableObject.getTopLevelScope(this) instanceof Window) || getWindow().getWebWindow() == null) { super.put(name, start, value); } else { final HtmlElement e = (HtmlElement) getDomNodeOrNull(); if (e != null) { e.setAttribute("data-" + decamelize(name), Context.toString(value)); } } }
Example #27
Source File: XMLDOMNodeList.java From HtmlUnit-Android with Apache License 2.0 | 5 votes |
/** * Creates an instance. * @param parentScope parent scope * @param attributeChangeSensitive indicates if the content of the collection may change when an attribute * of a descendant node of parentScope changes (attribute added, modified or removed) * @param description a text useful for debugging */ private XMLDOMNodeList(final ScriptableObject parentScope, final boolean attributeChangeSensitive, final String description) { setParentScope(parentScope); setPrototype(getPrototype(getClass())); description_ = description; attributeChangeSensitive_ = attributeChangeSensitive; }
Example #28
Source File: JSObject.java From HtmlUnit-Android with Apache License 2.0 | 5 votes |
/** * Calls a JavaScript method. * Equivalent to "this.methodName(args[0], args[1], ...)" in JavaScript. * * @param methodName the name of the JavaScript method to be invoked * @param args an array of Java object to be passed as arguments to the method * @return result result of the method * @throws JSException in case or error */ public Object call(final String methodName, final Object[] args) throws JSException { if (LOG.isInfoEnabled()) { LOG.info("JSObject call '" + methodName + "(" + Arrays.toString(args) + ")'"); } final Object jsResult = ScriptableObject.callMethod(scriptableObject_, methodName, args); if (jsResult instanceof ScriptableObject) { return new JSObject((ScriptableObject) jsResult); } if (jsResult instanceof ConsString) { return ((ConsString) jsResult).toString(); } return jsResult; }
Example #29
Source File: ProxyAutoConfig.java From HtmlUnit-Android with Apache License 2.0 | 5 votes |
private void defineMethod(final String methodName, final Scriptable scope) { for (Method method : getClass().getMethods()) { if (method.getName().equals(methodName)) { final FunctionObject functionObject = new FunctionObject(methodName, method, scope); ((ScriptableObject) scope).defineProperty(methodName, functionObject, ScriptableObject.EMPTY); } } }
Example #30
Source File: DialogWindow.java From htmlunit with Apache License 2.0 | 5 votes |
/** * {@inheritDoc} */ @Override public <T> void setScriptableObject(final T scriptObject) { if (scriptObject instanceof ScriptableObject) { ((ScriptableObject) scriptObject).put("dialogArguments", (ScriptableObject) scriptObject, arguments_); } super.setScriptableObject(scriptObject); }