com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine. 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: AudioContext.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * The decodeAudioData() method of the BaseAudioContext Interface is used to asynchronously
 * decode audio file data contained in an ArrayBuffer. In this case the ArrayBuffer is
 * loaded from XMLHttpRequest and FileReader.
 * The decoded AudioBuffer is resampled to the AudioContext's sampling rate,
 * then passed to a callback or promise.
 * @param buffer An ArrayBuffer containing the audio data to be decoded, usually grabbed
 * from XMLHttpRequest, WindowOrWorkerGlobalScope.fetch() or FileReader
 * @param success A callback function to be invoked when the decoding successfully finishes.
 * The single argument to this callback is an AudioBuffer representing the decodedData
 * (the decoded PCM audio data). Usually you'll want to put the decoded data into
 * an AudioBufferSourceNode, from which it can be played and manipulated how you want.
 * @param error An optional error callback, to be invoked if an error occurs
 * when the audio data is being decoded.
 * @return the promise or null
 */
@JsxFunction
public Promise decodeAudioData(final NativeArrayBuffer buffer, final Function success, final Function error) {
    final Window window = getWindow();
    final HtmlPage owningPage = (HtmlPage) window.getDocument().getPage();
    final JavaScriptEngine jsEngine =
            (JavaScriptEngine) window.getWebWindow().getWebClient().getJavaScriptEngine();

    if (error != null) {
        jsEngine.addPostponedAction(new PostponedAction(owningPage) {
            @Override
            public void execute() throws Exception {
                jsEngine.callFunction(owningPage, error, getParentScope(), AudioContext.this, new Object[] {});
            }
        });
        return null;
    }

    final Promise promise = Promise.reject(Context.getCurrentContext(), AudioContext.this, new Object[] {}, null);
    return promise;
}
 
Example #2
Source File: WebClient.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance that will use the specified {@link BrowserVersion} and proxy server.
 * @param browserVersion the browser version to simulate
 * @param proxyHost the server that will act as proxy or null for no proxy
 * @param proxyPort the port to use on the proxy server
 */
public WebClient(final BrowserVersion browserVersion, final String proxyHost, final int proxyPort) {
    WebAssert.notNull("browserVersion", browserVersion);

    browserVersion_ = browserVersion;
    if (proxyHost == null) {
        getOptions().setProxyConfig(new ProxyConfig());
    }
    else {
        getOptions().setProxyConfig(new ProxyConfig(proxyHost, proxyPort));
    }

    webConnection_ = createWebConnection(); // this has to be done after the browser version was set
    scriptEngine_ = new JavaScriptEngine(this);
    loadQueue_ = new ArrayList<>();

    // The window must be constructed AFTER the script engine.
    addWebWindowListener(new CurrentWindowTracker(this));
    currentWindow_ = new TopLevelWindow("", this);
    fireWindowOpened(new WebWindowEvent(currentWindow_, WebWindowEvent.OPEN, null, null));

    if (getBrowserVersion().hasFeature(JS_XML_SUPPORT_VIA_ACTIVEXOBJECT)) {
        initMSXMLActiveX();
    }
}
 
Example #3
Source File: HtmlUnitRegExpProxy2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #4
Source File: HtmlUnitRegExpProxy2Test.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Tests if custom patch is still needed.
 */
@Test
public void needCustomFix() {
    final WebClient client = getWebClient();
    final ContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
    final Context ctx = cf.enterContext();
    try {
        final ScriptableObject topScope = ctx.initStandardObjects();
        topScope.put("str", topScope, str_);
        topScope.put("text", topScope, text_);
        topScope.put("expected", topScope, expected_);
        assertEquals(begin_ + end_, text_.replaceAll(str_, ""));
        try {
            ctx.evaluateString(topScope, src_, "test script", 0, null);
        }
        catch (final JavaScriptException e) {
            assertTrue(e.getMessage().indexOf("Expected >") == 0);
        }
    }
    finally {
        Context.exit();
    }
}
 
Example #5
Source File: DownloadBehaviorJob.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Performs the download and calls the callback method.
 */
@Override
public void run() {
    final Scriptable scope = callback_.getParentScope();
    final WebRequest request = new WebRequest(url_);
    try {
        final WebResponse webResponse = client_.loadWebResponse(request);
        final String content = webResponse.getContentAsString();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Downloaded content: " + StringUtils.abbreviate(content, 512));
        }
        final Object[] args = new Object[] {content};
        final ContextAction action = new ContextAction() {
            @Override
            public Object run(final Context cx) {
                callback_.call(cx, scope, scope, args);
                return null;
            }
        };
        final ContextFactory cf = ((JavaScriptEngine) client_.getJavaScriptEngine()).getContextFactory();
        cf.call(action);
    }
    catch (final IOException e) {
        LOG.error("Behavior #default#download: Cannot download " + url_, e);
    }
}
 
Example #6
Source File: XMLHTTPRequest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the state as specified and invokes the state change handler if one has been set.
 * @param state the new state
 * @param context the context within which the state change handler is to be invoked;
 *     if {@code null}, the current thread's context is used
 */
private void setState(final int state, Context context) {
    state_ = state;

    if (stateChangeHandler_ != null && !openedMultipleTimes_) {
        final Scriptable scope = stateChangeHandler_.getParentScope();
        final JavaScriptEngine jsEngine = (JavaScriptEngine) containingPage_.getWebClient().getJavaScriptEngine();

        if (LOG.isDebugEnabled()) {
            LOG.debug("Calling onreadystatechange handler for state " + state);
        }
        final Object[] params = ArrayUtils.EMPTY_OBJECT_ARRAY;

        jsEngine.callFunction(containingPage_, stateChangeHandler_, scope, this, params);
        if (LOG.isDebugEnabled()) {
            if (context == null) {
                context = Context.getCurrentContext();
            }
            LOG.debug("onreadystatechange handler: " + context.decompileFunction(stateChangeHandler_, 4));
            LOG.debug("Calling onreadystatechange handler for state " + state + ". Done.");
        }
    }
}
 
Example #7
Source File: DomElement.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * Fires the event on the element. Nothing is done if JavaScript is disabled.
 * @param event the event to fire
 * @return the execution result, or {@code null} if nothing is executed
 */
public ScriptResult fireEvent(final Event event) {
    final WebClient client = getPage().getWebClient();
    if (!client.isJavaScriptEnabled()) {
        return null;
    }

    if (!handles(event)) {
        return null;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Firing " + event);
    }

    final EventTarget jsElt = getScriptableObject();
    final HtmlUnitContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
    final ScriptResult result = cf.callSecured(cx -> jsElt.fireEvent(event), getHtmlPageOrNull());
    if (event.isAborted(result)) {
        preventDefault();
    }
    return result;
}
 
Example #8
Source File: DedicatedWorkerGlobalScope.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
void messagePosted(final Object message) {
    final MessageEvent event = new MessageEvent();
    event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin_, "",
                                owningWindow_, Undefined.instance);
    event.setParentScope(owningWindow_);
    event.setPrototype(owningWindow_.getPrototype(event.getClass()));

    final JavaScriptEngine jsEngine =
            (JavaScriptEngine) owningWindow_.getWebWindow().getWebClient().getJavaScriptEngine();
    final ContextAction<Object> action = new ContextAction<Object>() {
        @Override
        public Object run(final Context cx) {
            executeEvent(cx, event);
            return null;
        }
    };

    final ContextFactory cf = jsEngine.getContextFactory();

    final JavaScriptJob job = new WorkerJob(cf, action, "messagePosted: " + Context.toString(message));

    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    owningWindow_.getWebWindow().getJobManager().addJob(job, page);
}
 
Example #9
Source File: XMLHttpRequest.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Invokes the onerror handler if one has been set.
 * @param context the context within which the onerror handler is to be invoked;
 *                if {@code null}, the current thread's context is used.
 */
private void processError(Context context) {
    if (errorHandler_ != null) {
        final Scriptable scope = errorHandler_.getParentScope();
        final JavaScriptEngine jsEngine = (JavaScriptEngine) containingPage_.getWebClient().getJavaScriptEngine();

        final Object[] params = new Event[] {new ProgressEvent(this, Event.TYPE_ERROR)};

        if (LOG.isDebugEnabled()) {
            LOG.debug("Calling onerror handler");
        }
        jsEngine.callFunction(containingPage_, errorHandler_, this, scope, params);
        if (LOG.isDebugEnabled()) {
            if (context == null) {
                context = Context.getCurrentContext();
            }
            LOG.debug("onerror handler: " + context.decompileFunction(errorHandler_, 4));
            LOG.debug("Calling onerror handler done.");
        }
    }
}
 
Example #10
Source File: DedicatedWorkerGlobalScope.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 * @param browserVersion the simulated browser version
 * @param worker the started worker
 * @throws Exception in case of problem
 */
DedicatedWorkerGlobalScope(final Window owningWindow, final Context context, final BrowserVersion browserVersion,
        final Worker worker) throws Exception {
    context.initSafeStandardObjects(this);

    ClassConfiguration config = AbstractJavaScriptConfiguration.getClassConfiguration(
            (Class<? extends HtmlUnitScriptable>) DedicatedWorkerGlobalScope.class.getSuperclass(),
            browserVersion);
    final HtmlUnitScriptable parentPrototype = JavaScriptEngine.configureClass(config, null, browserVersion);

    config = AbstractJavaScriptConfiguration.getClassConfiguration(
                            DedicatedWorkerGlobalScope.class, browserVersion);
    final HtmlUnitScriptable prototype = JavaScriptEngine.configureClass(config, null, browserVersion);
    prototype.setPrototype(parentPrototype);
    setPrototype(prototype);

    owningWindow_ = owningWindow;
    final URL currentURL = owningWindow.getWebWindow().getEnclosedPage().getUrl();
    origin_ = currentURL.getProtocol() + "://" + currentURL.getHost() + ':' + currentURL.getPort();

    worker_ = worker;
}
 
Example #11
Source File: NodeList.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Calls the {@code callback} given in parameter once for each value pair in the list, in insertion order.
 * @param callback function to execute for each element
 */
@JsxFunction({CHROME, FF, FF68, FF60})
public void forEach(final Object callback) {
    final List<DomNode> nodes = getElements();

    final WebClient client = getWindow().getWebWindow().getWebClient();
    final HtmlUnitContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();

    final ContextAction<Object> contextAction = new ContextAction<Object>() {
        @Override
        public Object run(final Context cx) {
            final Function function = (Function) callback;
            final Scriptable scope = getParentScope();
            for (int i = 0; i < nodes.size(); i++) {
                function.call(cx, scope, NodeList.this, new Object[] {
                        nodes.get(i).getScriptableObject(), i, NodeList.this});
            }
            return null;
        }
    };
    cf.call(contextAction);
}
 
Example #12
Source File: XMLHTTPRequest.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the state as specified and invokes the state change handler if one has been set.
 * @param state the new state
 * @param context the context within which the state change handler is to be invoked;
 *     if {@code null}, the current thread's context is used
 */
private void setState(final int state, Context context) {
    state_ = state;

    if (stateChangeHandler_ != null && !openedMultipleTimes_) {
        final Scriptable scope = stateChangeHandler_.getParentScope();
        final JavaScriptEngine jsEngine = (JavaScriptEngine) containingPage_.getWebClient().getJavaScriptEngine();

        if (LOG.isDebugEnabled()) {
            LOG.debug("Calling onreadystatechange handler for state " + state);
        }
        final Object[] params = ArrayUtils.EMPTY_OBJECT_ARRAY;

        jsEngine.callFunction(containingPage_, stateChangeHandler_, scope, this, params);
        if (LOG.isDebugEnabled()) {
            if (context == null) {
                context = Context.getCurrentContext();
            }
            LOG.debug("onreadystatechange handler: " + context.decompileFunction(stateChangeHandler_, 4));
            LOG.debug("Calling onreadystatechange handler for state " + state + ". Done.");
        }
    }
}
 
Example #13
Source File: DedicatedWorkerGlobalScope.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor.
 * @param browserVersion the simulated browser version
 * @param worker the started worker
 * @throws Exception in case of problem
 */
DedicatedWorkerGlobalScope(final Window owningWindow, final Context context, final BrowserVersion browserVersion,
        final Worker worker) throws Exception {
    context.initStandardObjects(this);

    final ClassConfiguration config = AbstractJavaScriptConfiguration.getClassConfiguration(
            DedicatedWorkerGlobalScope.class, browserVersion);
    final HtmlUnitScriptable prototype = JavaScriptEngine.configureClass(config, null, browserVersion);
    setPrototype(prototype);

    owningWindow_ = owningWindow;
    final URL currentURL = owningWindow.getWebWindow().getEnclosedPage().getUrl();
    origin_ = currentURL.getProtocol() + "://" + currentURL.getHost() + ':' + currentURL.getPort();

    worker_ = worker;
}
 
Example #14
Source File: DownloadBehaviorJob.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Performs the download and calls the callback method.
 */
@Override
public void run() {
    final Scriptable scope = callback_.getParentScope();
    final WebRequest request = new WebRequest(url_);
    try {
        final WebResponse webResponse = client_.loadWebResponse(request);
        final String content = webResponse.getContentAsString();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Downloaded content: " + StringUtils.abbreviate(content, 512));
        }
        final Object[] args = new Object[] {content};
        final ContextFactory cf = ((JavaScriptEngine) client_.getJavaScriptEngine()).getContextFactory();
        cf.call(cx -> {
            callback_.call(cx, scope, scope, args);
            return null;
        });
    }
    catch (final IOException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Behavior #default#download: Cannot download " + url_, e);
        }
    }
}
 
Example #15
Source File: MessagePort.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Posts a message.
 * @param message the object passed to the window
 * @param transfer an optional sequence of Transferable objects
 * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage">MDN documentation</a>
 */
@JsxFunction
public void postMessage(final String message, final Object transfer) {
    if (port1_ != null) {
        final Window w = getWindow();
        final URL currentURL = w.getWebWindow().getEnclosedPage().getUrl();
        final MessageEvent event = new MessageEvent();
        final String origin = currentURL.getProtocol() + "://" + currentURL.getHost() + ':' + currentURL.getPort();
        event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin, "", w, transfer);
        event.setParentScope(port1_);
        event.setPrototype(getPrototype(event.getClass()));

        final JavaScriptEngine jsEngine
            = (JavaScriptEngine) w.getWebWindow().getWebClient().getJavaScriptEngine();
        final PostponedAction action = new PostponedAction(w.getWebWindow().getEnclosedPage()) {
            @Override
            public void execute() throws Exception {
                final ContextFactory cf = jsEngine.getContextFactory();
                cf.call(cx -> port1_.dispatchEvent(event));
            }
        };
        jsEngine.addPostponedAction(action);
    }
}
 
Example #16
Source File: XMLHttpRequest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Invokes the onerror handler if one has been set.
 * @param context the context within which the onerror handler is to be invoked;
 *                if {@code null}, the current thread's context is used.
 */
private void processError(Context context) {
    final Function onError = getOnerror();
    if (onError != null) {
        final Scriptable scope = onError.getParentScope();
        final JavaScriptEngine jsEngine = (JavaScriptEngine) containingPage_.getWebClient().getJavaScriptEngine();

        final Object[] params = {new ProgressEvent(this, Event.TYPE_ERROR)};

        if (LOG.isDebugEnabled()) {
            LOG.debug("Calling onerror handler");
        }
        jsEngine.callFunction(containingPage_, onError, this, scope, params);
        if (LOG.isDebugEnabled()) {
            if (context == null) {
                context = Context.getCurrentContext();
            }
            LOG.debug("onerror handler: " + context.decompileFunction(onError, 4));
            LOG.debug("Calling onerror handler done.");
        }
    }
}
 
Example #17
Source File: DedicatedWorkerGlobalScope.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
void messagePosted(final Object message) {
    final MessageEvent event = new MessageEvent();
    event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin_, "", owningWindow_, null);
    event.setParentScope(owningWindow_);
    event.setPrototype(owningWindow_.getPrototype(event.getClass()));

    final JavaScriptEngine jsEngine =
            (JavaScriptEngine) owningWindow_.getWebWindow().getWebClient().getJavaScriptEngine();
    final ContextAction action = new ContextAction() {
        @Override
        public Object run(final Context cx) {
            return executeEvent(cx, event);
        }
    };

    final ContextFactory cf = jsEngine.getContextFactory();

    final JavaScriptJob job = new WorkerJob(cf, action, "messagePosted: " + Context.toString(message));

    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    owningWindow_.getWebWindow().getJobManager().addJob(job, page);
}
 
Example #18
Source File: WebSocket.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private void callFunction(final Function function, final Object[] args) {
    if (function == null) {
        return;
    }
    final Scriptable scope = function.getParentScope();
    final JavaScriptEngine engine
        = (JavaScriptEngine) containingPage_.getWebClient().getJavaScriptEngine();
    engine.callFunction(containingPage_, function, scope, this, args);
}
 
Example #19
Source File: HtmlPage.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private ScriptResult executeJavaScriptFunction(final Function function, final Scriptable thisObject,
        final Object[] args, final DomNode htmlElementScope) {

    final JavaScriptEngine engine = (JavaScriptEngine) getWebClient().getJavaScriptEngine();
    final Object result = engine.callFunction(this, function, thisObject, args, htmlElementScope);

    return new ScriptResult(result, getWebClient().getCurrentWindow().getEnclosedPage());
}
 
Example #20
Source File: MessagePort.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Posts a message.
 * @param message the object passed to the window
 * @param transfer an optional sequence of Transferable objects
 * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage">MDN documentation</a>
 */
@JsxFunction
public void postMessage(final String message, final Object transfer) {
    if (port1_ != null) {
        final Window w = getWindow();
        final URL currentURL = w.getWebWindow().getEnclosedPage().getUrl();
        final MessageEvent event = new MessageEvent();
        final String origin = currentURL.getProtocol() + "://" + currentURL.getHost() + ':' + currentURL.getPort();
        event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin, "", w, transfer);
        event.setParentScope(port1_);
        event.setPrototype(getPrototype(event.getClass()));

        final JavaScriptEngine jsEngine
            = (JavaScriptEngine) w.getWebWindow().getWebClient().getJavaScriptEngine();
        final PostponedAction action = new PostponedAction(w.getWebWindow().getEnclosedPage()) {
            @Override
            public void execute() throws Exception {
                final ContextAction contextAction = new ContextAction() {
                    @Override
                    public Object run(final Context cx) {
                        return port1_.dispatchEvent(event);
                    }
                };

                final ContextFactory cf = jsEngine.getContextFactory();
                cf.call(contextAction);
            }
        };
        jsEngine.addPostponedAction(action);
    }
}
 
Example #21
Source File: DomElement.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * Fires the event on the element. Nothing is done if JavaScript is disabled.
 * @param event the event to fire
 * @return the execution result, or {@code null} if nothing is executed
 */
public ScriptResult fireEvent(final Event event) {
    final WebClient client = getPage().getWebClient();
    if (!client.getOptions().isJavaScriptEnabled()) {
        return null;
    }

    if (!handles(event)) {
        return null;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Firing " + event);
    }
    final EventTarget jsElt = (EventTarget) getScriptableObject();
    final ContextAction action = new ContextAction() {
        @Override
        public Object run(final Context cx) {
            return jsElt.fireEvent(event);
        }
    };

    final ContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
    final ScriptResult result = (ScriptResult) cf.call(action);
    if (event.isAborted(result)) {
        preventDefault();
    }
    return result;
}
 
Example #22
Source File: WebSocket.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private void fire(final Event evt) {
    evt.setTarget(this);
    evt.setParentScope(getParentScope());
    evt.setPrototype(getPrototype(evt.getClass()));

    final JavaScriptEngine engine
        = (JavaScriptEngine) containingPage_.getWebClient().getJavaScriptEngine();
    engine.getContextFactory().call(new ContextAction() {
        @Override
        public ScriptResult run(final Context cx) {
            return executeEventLocally(evt);
        }
    });
}
 
Example #23
Source File: DedicatedWorkerGlobalScope.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
void loadAndExecute(final String url, final Context context) throws IOException {
    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    final URL fullUrl = page.getFullyQualifiedUrl(url);

    final WebClient webClient = owningWindow_.getWebWindow().getWebClient();

    final WebRequest webRequest = new WebRequest(fullUrl);
    final WebResponse response = webClient.loadWebResponse(webRequest);
    final String scriptCode = response.getContentAsString();
    final JavaScriptEngine javaScriptEngine = (JavaScriptEngine) webClient.getJavaScriptEngine();

    final DedicatedWorkerGlobalScope thisScope = this;
    final ContextAction action = new ContextAction() {
        @Override
        public Object run(final Context cx) {
            final Script script = javaScriptEngine.compile(page, thisScope, scriptCode,
                    fullUrl.toExternalForm(), 1);
            return javaScriptEngine.execute(page, thisScope, script);
        }
    };

    final ContextFactory cf = javaScriptEngine.getContextFactory();

    if (context != null) {
        action.run(context);
    }
    else {
        final JavaScriptJob job = new WorkerJob(cf, action, "loadAndExecute " + url);

        owningWindow_.getWebWindow().getJobManager().addJob(job, page);
    }
}
 
Example #24
Source File: MutationObserver.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void attributeReplaced(final HtmlAttributeChangeEvent event) {
    final HtmlElement target = event.getHtmlElement();
    if (subtree_ || target == node_.getDomNodeOrDie()) {
        final String attributeName = event.getName();
        if (attributeFilter_ == null || attributeFilter_.contains(attributeName)) {
            final MutationRecord mutationRecord = new MutationRecord();
            final Scriptable scope = getParentScope();
            mutationRecord.setParentScope(scope);
            mutationRecord.setPrototype(getPrototype(mutationRecord.getClass()));

            mutationRecord.setAttributeName(attributeName);
            mutationRecord.setType("attributes");
            mutationRecord.setTarget((ScriptableObject) target.getScriptableObject());
            if (attributeOldValue_) {
                mutationRecord.setOldValue(event.getValue());
            }

            final Window window = getWindow();
            final HtmlPage owningPage = (HtmlPage) window.getDocument().getPage();
            final JavaScriptEngine jsEngine =
                    (JavaScriptEngine) window.getWebWindow().getWebClient().getJavaScriptEngine();
            jsEngine.addPostponedAction(new PostponedAction(owningPage) {
                @Override
                public void execute() throws Exception {
                    final NativeArray array = new NativeArray(new Object[] {mutationRecord});
                    ScriptRuntime.setBuiltinProtoAndParent(array, scope, TopLevel.Builtins.Array);
                    jsEngine.callFunction(owningPage, function_, scope,
                                            MutationObserver.this, new Object[] {array});
                }
            });
        }
    }
}
 
Example #25
Source File: Intl.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private void define(final Class<? extends SimpleScriptable> c, final BrowserVersion browserVersion) {
    try {
        final ClassConfiguration config = AbstractJavaScriptConfiguration.getClassConfiguration(c, browserVersion);
        final HtmlUnitScriptable prototype = JavaScriptEngine.configureClass(config, this, browserVersion);
        final FunctionObject functionObject =
                new RecursiveFunctionObject(c.getSimpleName(), config.getJsConstructor(), this);
        if (c == V8BreakIterator.class) {
            prototype.setClassName("v8BreakIterator");
        }
        functionObject.addAsConstructor(this, prototype);
    }
    catch (final Exception e) {
        throw Context.throwAsScriptRuntimeEx(e);
    }
}
 
Example #26
Source File: DedicatedWorkerGlobalScope.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Posts a message to the {@link Worker} in the page's context.
 * @param message the message
 */
@JsxFunction
public void postMessage(final Object message) {
    final MessageEvent event = new MessageEvent();
    event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin_, "", owningWindow_, null);
    event.setParentScope(owningWindow_);
    event.setPrototype(owningWindow_.getPrototype(event.getClass()));

    if (LOG.isDebugEnabled()) {
        LOG.debug("[DedicatedWorker] postMessage: {}" + message);
    }
    final JavaScriptEngine jsEngine =
            (JavaScriptEngine) owningWindow_.getWebWindow().getWebClient().getJavaScriptEngine();
    final ContextAction action = new ContextAction() {
        @Override
        public Object run(final Context cx) {
            worker_.getEventListenersContainer().executeCapturingListeners(event, null);
            final Object[] args = new Object[] {event};
            return worker_.getEventListenersContainer().executeBubblingListeners(event, args, args);
        }
    };

    final ContextFactory cf = jsEngine.getContextFactory();

    final JavaScriptJob job = new WorkerJob(cf, action, "postMessage: " + Context.toString(message));

    final HtmlPage page = (HtmlPage) owningWindow_.getDocument().getPage();
    owningWindow_.getWebWindow().getJobManager().addJob(job, page);
}
 
Example #27
Source File: XMLDocument.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public SimpleScriptable makeScriptableFor(final DomNode domNode) {
    final SimpleScriptable scriptable;

    // TODO: cleanup, getScriptObject() should be used!!!
    if (domNode instanceof DomElement && !(domNode instanceof HtmlElement)) {
        if (domNode instanceof SvgElement) {
            final Class<? extends HtmlUnitScriptable> javaScriptClass
                = ((JavaScriptEngine) getWindow().getWebWindow().getWebClient()
                    .getJavaScriptEngine()).getJavaScriptClass(domNode.getClass());
            try {
                scriptable = (SimpleScriptable) javaScriptClass.newInstance();
            }
            catch (final Exception e) {
                throw Context.throwAsScriptRuntimeEx(e);
            }
        }
        else {
            scriptable = new Element();
        }
    }
    else if (domNode instanceof DomAttr) {
        scriptable = new Attr();
    }
    else {
        return super.makeScriptableFor(domNode);
    }

    scriptable.setPrototype(getPrototype(scriptable.getClass()));
    scriptable.setParentScope(getParentScope());
    scriptable.setDomNode(domNode);
    return scriptable;
}
 
Example #28
Source File: WebClient.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * When we deserialize, re-initializie transient fields.
 * @param in the object input stream
 * @throws IOException if an error occurs
 * @throws ClassNotFoundException if an error occurs
 */
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();

    webConnection_ = new HttpWebConnection(this);
    scriptEngine_ = new JavaScriptEngine(this);
    jobManagers_ = Collections.synchronizedList(new ArrayList<WeakReference<JavaScriptJobManager>>());
    loadQueue_ = new ArrayList<>();

    if (getBrowserVersion().hasFeature(JS_XML_SUPPORT_VIA_ACTIVEXOBJECT)) {
        initMSXMLActiveX();
    }
}
 
Example #29
Source File: MutationObserver.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void characterDataChanged(final CharacterDataChangeEvent event) {
    final ScriptableObject target = event.getCharacterData().getScriptableObject();
    if (subtree_ || target == node_) {
        final MutationRecord mutationRecord = new MutationRecord();
        final Scriptable scope = getParentScope();
        mutationRecord.setParentScope(scope);
        mutationRecord.setPrototype(getPrototype(mutationRecord.getClass()));

        mutationRecord.setType("characterData");
        mutationRecord.setTarget(target);
        if (characterDataOldValue_) {
            mutationRecord.setOldValue(event.getOldValue());
        }

        final Window window = getWindow();
        final HtmlPage owningPage = (HtmlPage) window.getDocument().getPage();
        final JavaScriptEngine jsEngine =
                (JavaScriptEngine) window.getWebWindow().getWebClient().getJavaScriptEngine();
        jsEngine.addPostponedAction(new PostponedAction(owningPage) {
            @Override
            public void execute() throws Exception {
                final NativeArray array = new NativeArray(new Object[] {mutationRecord});
                ScriptRuntime.setBuiltinProtoAndParent(array, scope, TopLevel.Builtins.Array);
                jsEngine.callFunction(owningPage, function_, scope, MutationObserver.this, new Object[] {array});
            }
        });
    }
}
 
Example #30
Source File: SimpleWebTestCase.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the number of JS threads remaining from unit tests run before.
 * This should be always 0.
 */
@Before
public void before() {
    if (webClient_ != null && webClient_.getJavaScriptEngine() instanceof JavaScriptEngine) {
        assertTrue(getJavaScriptThreads().isEmpty());
    }
}