Search in sources :

Example 1 with Scriptable

use of net.sourceforge.htmlunit.corejs.javascript.Scriptable in project htmlunit by HtmlUnit.

the class ActiveXObject method jsConstructor.

/**
 * This method
 * <ol>
 *   <li>instantiates the MSXML (ActiveX) object if requested (<code>XMLDOMDocument</code>,
 *      <code>XMLHTTPRequest</code>, <code>XSLTemplate</code>)
 *   <li>searches the map specified in the <code>WebClient</code> class for the Java object to instantiate based
 *      on the ActiveXObject constructor String
 *   <li>uses <code>ActiveXObjectImpl</code> to initiate Jacob.
 * </ol>
 *
 * @param cx the current context
 * @param args the arguments to the ActiveXObject constructor
 * @param ctorObj the function object
 * @param inNewExpr Is new or not
 * @return the java object to allow JavaScript to access
 */
@JsxConstructor
public static Scriptable jsConstructor(final Context cx, final Object[] args, final Function ctorObj, final boolean inNewExpr) {
    if (args.length < 1 || args.length > 2) {
        throw Context.reportRuntimeError("ActiveXObject Error: constructor must have one or two String parameters.");
    }
    if (Undefined.isUndefined(args[0])) {
        throw Context.reportRuntimeError("ActiveXObject Error: constructor parameter is undefined.");
    }
    if (!(args[0] instanceof String)) {
        throw Context.reportRuntimeError("ActiveXObject Error: constructor parameter must be a String.");
    }
    final String activeXName = (String) args[0];
    final WebWindow window = getWindow(ctorObj).getWebWindow();
    final MSXMLActiveXObjectFactory factory = window.getWebClient().getMSXMLActiveXObjectFactory();
    if (factory.supports(activeXName)) {
        final Scriptable scriptable = factory.create(activeXName, window);
        if (scriptable != null) {
            return scriptable;
        }
    }
    final WebClient webClient = getWindow(ctorObj).getWebWindow().getWebClient();
    final Map<String, String> map = webClient.getActiveXObjectMap();
    if (map != null) {
        final String xClassString = map.get(activeXName);
        if (xClassString != null) {
            try {
                final Class<?> xClass = Class.forName(xClassString);
                final Object object = xClass.newInstance();
                return Context.toObject(object, ctorObj);
            } catch (final Exception e) {
                throw Context.reportRuntimeError("ActiveXObject Error: failed instantiating class " + xClassString + " because " + e.getMessage() + ".");
            }
        }
    }
    if (webClient.getOptions().isActiveXNative() && System.getProperty("os.name").contains("Windows")) {
        try {
            return new ActiveXObjectImpl(activeXName);
        } catch (final Exception e) {
            LOG.warn("Error initiating Jacob", e);
        }
    }
    if (LOG.isWarnEnabled()) {
        LOG.warn("Automation server can't create object for '" + activeXName + "'.");
    }
    throw Context.reportRuntimeError("Automation server can't create object for '" + activeXName + "'.");
}
Also used : MSXMLActiveXObjectFactory(com.gargoylesoftware.htmlunit.activex.javascript.msxml.MSXMLActiveXObjectFactory) Scriptable(net.sourceforge.htmlunit.corejs.javascript.Scriptable) HtmlUnitScriptable(com.gargoylesoftware.htmlunit.javascript.HtmlUnitScriptable) WebClient(com.gargoylesoftware.htmlunit.WebClient) WebWindow(com.gargoylesoftware.htmlunit.WebWindow) JsxConstructor(com.gargoylesoftware.htmlunit.javascript.configuration.JsxConstructor)

Example 2 with Scriptable

use of net.sourceforge.htmlunit.corejs.javascript.Scriptable in project htmlunit by HtmlUnit.

the class DebugFrameImpl method getFunctionName.

/**
 * Returns the name of the function corresponding to this frame, if it is a function and it has
 * a name. If the function does not have a name, this method will try to return the name under
 * which it was referenced. See <a
 * href="http://www.digital-web.com/articles/scope_in_javascript/">this page</a> for a good
 * explanation of how the <tt>thisObj</tt> plays into this guess.
 *
 * @param thisObj the object via which the function was referenced, used to try to guess a
 *        function name if the function is anonymous
 * @return the name of the function corresponding to this frame
 */
private String getFunctionName(final Scriptable thisObj) {
    if (functionOrScript_.isFunction()) {
        final String name = functionOrScript_.getFunctionName();
        if (name != null && !name.isEmpty()) {
            // A named function -- we can just return the name.
            return name;
        }
        // on our HtmlUnitScriptable we need to avoid looking at the properties we have defined => TODO: improve it
        if (thisObj instanceof HtmlUnitScriptable) {
            return "[anonymous]";
        }
        Scriptable obj = thisObj;
        while (obj != null) {
            for (final Object id : obj.getIds()) {
                if (id instanceof String) {
                    final String s = (String) id;
                    if (obj instanceof ScriptableObject) {
                        Object o = ((ScriptableObject) obj).getGetterOrSetter(s, 0, thisObj, false);
                        if (o == null) {
                            o = ((ScriptableObject) obj).getGetterOrSetter(s, 0, thisObj, true);
                            if (o != null) {
                                return "__defineSetter__ " + s;
                            }
                        } else {
                            return "__defineGetter__ " + s;
                        }
                    }
                    final Object o;
                    try {
                        // within a try block as this sometimes throws (not sure why)
                        o = obj.get(s, obj);
                    } catch (final Exception e) {
                        return "[anonymous]";
                    }
                    if (o instanceof NativeFunction) {
                        final NativeFunction f = (NativeFunction) o;
                        if (f.getDebuggableView() == functionOrScript_) {
                            return s;
                        }
                    }
                }
            }
            obj = obj.getPrototype();
        }
        // Unable to intuit a name -- doh!
        return "[anonymous]";
    }
    // Just a script -- no function name.
    return "[script]";
}
Also used : ScriptableObject(net.sourceforge.htmlunit.corejs.javascript.ScriptableObject) NativeFunction(net.sourceforge.htmlunit.corejs.javascript.NativeFunction) IdFunctionObject(net.sourceforge.htmlunit.corejs.javascript.IdFunctionObject) ScriptableObject(net.sourceforge.htmlunit.corejs.javascript.ScriptableObject) Scriptable(net.sourceforge.htmlunit.corejs.javascript.Scriptable) JavaScriptException(net.sourceforge.htmlunit.corejs.javascript.JavaScriptException)

Example 3 with Scriptable

use of net.sourceforge.htmlunit.corejs.javascript.Scriptable in project htmlunit by HtmlUnit.

the class Blob method text.

/**
 * @return a Promise that resolves with a string containing the
 * contents of the blob, interpreted as UTF-8.
 */
@JsxFunction({ CHROME, EDGE, FF, FF_ESR })
public Object text() {
    final Scriptable scope = ScriptableObject.getTopLevelScope(this);
    final LambdaConstructor ctor = (LambdaConstructor) getProperty(scope, "Promise");
    try {
        final LambdaFunction resolve = (LambdaFunction) getProperty(ctor, "resolve");
        return resolve.call(Context.getCurrentContext(), this, ctor, new Object[] { getBackend().getText() });
    } catch (final IOException e) {
        final LambdaFunction reject = (LambdaFunction) getProperty(ctor, "reject");
        return reject.call(Context.getCurrentContext(), this, ctor, new Object[] { e.getMessage() });
    }
}
Also used : LambdaConstructor(net.sourceforge.htmlunit.corejs.javascript.LambdaConstructor) LambdaFunction(net.sourceforge.htmlunit.corejs.javascript.LambdaFunction) ScriptableObject(net.sourceforge.htmlunit.corejs.javascript.ScriptableObject) IOException(java.io.IOException) HtmlUnitScriptable(com.gargoylesoftware.htmlunit.javascript.HtmlUnitScriptable) Scriptable(net.sourceforge.htmlunit.corejs.javascript.Scriptable) JsxFunction(com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)

Example 4 with Scriptable

use of net.sourceforge.htmlunit.corejs.javascript.Scriptable in project htmlunit by HtmlUnit.

the class EventListenersContainer method executeEventListeners.

private void executeEventListeners(final int eventPhase, final Event event, final Object[] args) {
    final DomNode node = jsNode_.getDomNodeOrNull();
    // some event don't apply on all kind of nodes, for instance "blur"
    if (node != null && !node.handles(event)) {
        return;
    }
    final TypeContainer container = getTypeContainer(event.getType());
    final List<Scriptable> listeners = container.getListeners(eventPhase);
    if (!listeners.isEmpty()) {
        event.setCurrentTarget(jsNode_);
        final HtmlPage page;
        if (jsNode_ instanceof Window) {
            page = (HtmlPage) jsNode_.getDomNodeOrDie();
        } else {
            final Scriptable parentScope = jsNode_.getParentScope();
            if (parentScope instanceof Window) {
                page = (HtmlPage) ((Window) parentScope).getDomNodeOrDie();
            } else if (parentScope instanceof HTMLDocument) {
                page = ((HTMLDocument) parentScope).getPage();
            } else {
                page = ((HTMLElement) parentScope).getDomNodeOrDie().getHtmlPageOrNull();
            }
        }
        // no need for a copy, listeners are copy on write
        for (Scriptable listener : listeners) {
            boolean isPropertyHandler = false;
            if (listener == TypeContainer.EVENT_HANDLER_PLACEHOLDER) {
                listener = container.handler_;
                isPropertyHandler = true;
            }
            Function function = null;
            Scriptable thisObject = null;
            if (listener instanceof Function) {
                function = (Function) listener;
                thisObject = jsNode_;
            } else if (listener instanceof NativeObject) {
                final Object handleEvent = ScriptableObject.getProperty(listener, "handleEvent");
                if (handleEvent instanceof Function) {
                    function = (Function) handleEvent;
                    thisObject = listener;
                }
            }
            if (function != null) {
                final ScriptResult result = page.executeJavaScriptFunction(function, thisObject, args, node);
                // Return value is only honored for property handlers (Tested in Chrome/FF/IE11)
                if (isPropertyHandler && !ScriptResult.isUndefined(result)) {
                    event.handlePropertyHandlerReturnValue(result.getJavaScriptResult());
                }
            }
            if (event.isImmediatePropagationStopped()) {
                return;
            }
        }
    }
}
Also used : Window(com.gargoylesoftware.htmlunit.javascript.host.Window) NativeObject(net.sourceforge.htmlunit.corejs.javascript.NativeObject) ScriptResult(com.gargoylesoftware.htmlunit.ScriptResult) Function(net.sourceforge.htmlunit.corejs.javascript.Function) DomNode(com.gargoylesoftware.htmlunit.html.DomNode) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) HTMLDocument(com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument) NativeObject(net.sourceforge.htmlunit.corejs.javascript.NativeObject) ScriptableObject(net.sourceforge.htmlunit.corejs.javascript.ScriptableObject) Scriptable(net.sourceforge.htmlunit.corejs.javascript.Scriptable)

Example 5 with Scriptable

use of net.sourceforge.htmlunit.corejs.javascript.Scriptable in project htmlunit by HtmlUnit.

the class HTMLMediaElement method play.

/**
 * Begins playback of the media.
 *
 * @return a {@link Promise} which is fulfilled when playback has been started,
 *         or is rejected if for any reason playback cannot be started
 */
@JsxFunction
public Object play() {
    if (getBrowserVersion().hasFeature(JS_PROMISE)) {
        final Scriptable scope = ScriptableObject.getTopLevelScope(this);
        final LambdaConstructor ctor = (LambdaConstructor) getProperty(scope, "Promise");
        final LambdaFunction reject = (LambdaFunction) getProperty(ctor, "reject");
        return reject.call(Context.getCurrentContext(), this, ctor, new Object[] { new DOMException("HtmlUnit does not support media play().", DOMException.NOT_FOUND_ERR) });
    }
    return Undefined.instance;
}
Also used : DOMException(com.gargoylesoftware.htmlunit.javascript.host.dom.DOMException) LambdaConstructor(net.sourceforge.htmlunit.corejs.javascript.LambdaConstructor) LambdaFunction(net.sourceforge.htmlunit.corejs.javascript.LambdaFunction) Scriptable(net.sourceforge.htmlunit.corejs.javascript.Scriptable) JsxFunction(com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)

Aggregations

Scriptable (net.sourceforge.htmlunit.corejs.javascript.Scriptable)67 Context (net.sourceforge.htmlunit.corejs.javascript.Context)39 ContextAction (net.sourceforge.htmlunit.corejs.javascript.ContextAction)36 ScriptableObject (net.sourceforge.htmlunit.corejs.javascript.ScriptableObject)27 Test (org.junit.jupiter.api.Test)14 HtmlUnitScriptable (com.gargoylesoftware.htmlunit.javascript.HtmlUnitScriptable)12 JsxFunction (com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)12 Function (net.sourceforge.htmlunit.corejs.javascript.Function)10 HtmlPage (com.gargoylesoftware.htmlunit.html.HtmlPage)8 JavaScriptEngine (com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine)8 Window (com.gargoylesoftware.htmlunit.javascript.host.Window)7 ContextFactory (net.sourceforge.htmlunit.corejs.javascript.ContextFactory)7 WebClient (com.gargoylesoftware.htmlunit.WebClient)6 LambdaConstructor (net.sourceforge.htmlunit.corejs.javascript.LambdaConstructor)6 LambdaFunction (net.sourceforge.htmlunit.corejs.javascript.LambdaFunction)6 DomNode (com.gargoylesoftware.htmlunit.html.DomNode)5 Method (java.lang.reflect.Method)5 BaseFunction (net.sourceforge.htmlunit.corejs.javascript.BaseFunction)4 FunctionObject (net.sourceforge.htmlunit.corejs.javascript.FunctionObject)4 NativeObject (net.sourceforge.htmlunit.corejs.javascript.NativeObject)4