Search in sources :

Example 16 with JavaScriptEngine

use of com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine in project htmlunit by HtmlUnit.

the class AudioContext method decodeAudioData.

/**
 * 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 Object 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, "AudioContext.decodeAudioData") {

            @Override
            public void execute() throws Exception {
                jsEngine.callFunction(owningPage, error, getParentScope(), AudioContext.this, new Object[] {});
            }
        });
        return null;
    }
    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[] {});
}
Also used : Window(com.gargoylesoftware.htmlunit.javascript.host.Window) LambdaConstructor(net.sourceforge.htmlunit.corejs.javascript.LambdaConstructor) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) PostponedAction(com.gargoylesoftware.htmlunit.javascript.PostponedAction) ScriptableObject(net.sourceforge.htmlunit.corejs.javascript.ScriptableObject) LambdaFunction(net.sourceforge.htmlunit.corejs.javascript.LambdaFunction) Scriptable(net.sourceforge.htmlunit.corejs.javascript.Scriptable) JavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine) JsxFunction(com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)

Example 17 with JavaScriptEngine

use of com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine in project htmlunit by HtmlUnit.

the class HtmlPage method executeEventHandlersIfNeeded.

/**
 * Looks for and executes any appropriate event handlers. Looks for body and frame tags.
 * @param eventType either {@link Event#TYPE_LOAD}, {@link Event#TYPE_UNLOAD}, or {@link Event#TYPE_BEFORE_UNLOAD}
 * @return {@code true} if user accepted <tt>onbeforeunload</tt> (not relevant to other events)
 */
private boolean executeEventHandlersIfNeeded(final String eventType) {
    // If JavaScript isn't enabled, there's nothing for us to do.
    if (!getWebClient().isJavaScriptEnabled()) {
        return true;
    }
    // Execute the specified event on the document element.
    final WebWindow window = getEnclosingWindow();
    if (window.getScriptableObject() instanceof Window) {
        final Event event;
        if (eventType.equals(Event.TYPE_BEFORE_UNLOAD)) {
            event = new BeforeUnloadEvent(this, eventType);
        } else {
            event = new Event(this, eventType);
        }
        // here so it could be used with HtmlPage.
        if (LOG.isDebugEnabled()) {
            LOG.debug("Firing " + event);
        }
        final EventTarget jsNode;
        if (Event.TYPE_DOM_DOCUMENT_LOADED.equals(eventType)) {
            jsNode = this.getScriptableObject();
        } else {
            // The load/beforeunload/unload events target Document but paths Window only (tested in Chrome/FF)
            jsNode = window.getScriptableObject();
        }
        final HtmlUnitContextFactory cf = ((JavaScriptEngine) getWebClient().getJavaScriptEngine()).getContextFactory();
        cf.callSecured(cx -> jsNode.fireEvent(event), this);
        if (!isOnbeforeunloadAccepted(this, event)) {
            return false;
        }
    }
    // If this page was loaded in a frame, execute the version of the event specified on the frame tag.
    if (window instanceof FrameWindow) {
        final FrameWindow fw = (FrameWindow) window;
        final BaseFrameElement frame = fw.getFrameElement();
        // if part of a document fragment, then the load event is not triggered
        if (Event.TYPE_LOAD.equals(eventType) && frame.getParentNode() instanceof DomDocumentFragment) {
            return true;
        }
        if (frame.hasEventHandlers("on" + eventType)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Executing on" + eventType + " handler for " + frame);
            }
            if (window.getScriptableObject() instanceof Window) {
                final Event event;
                if (Event.TYPE_BEFORE_UNLOAD.equals(eventType)) {
                    event = new BeforeUnloadEvent(frame, eventType);
                } else {
                    // ff does not trigger the onload event in this case
                    if (PageDenied.BY_CONTENT_SECURIRY_POLICY == fw.getPageDenied() && hasFeature(JS_EVENT_LOAD_SUPPRESSED_BY_CONTENT_SECURIRY_POLICY)) {
                        return true;
                    }
                    event = new Event(frame, eventType);
                }
                // This fires the "load" event for the <frame> element which, like all non-window
                // load events, propagates up to Document but not Window.  The "load" event for
                // <frameset> on the other hand, like that of <body>, is handled above where it is
                // fired against Document and directed to Window.
                frame.fireEvent(event);
                if (!isOnbeforeunloadAccepted((HtmlPage) frame.getPage(), event)) {
                    return false;
                }
            }
        }
    }
    return true;
}
Also used : WebWindow(com.gargoylesoftware.htmlunit.WebWindow) Window(com.gargoylesoftware.htmlunit.javascript.host.Window) TopLevelWindow(com.gargoylesoftware.htmlunit.TopLevelWindow) HtmlUnitContextFactory(com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory) Event(com.gargoylesoftware.htmlunit.javascript.host.event.Event) BeforeUnloadEvent(com.gargoylesoftware.htmlunit.javascript.host.event.BeforeUnloadEvent) BeforeUnloadEvent(com.gargoylesoftware.htmlunit.javascript.host.event.BeforeUnloadEvent) EventTarget(com.gargoylesoftware.htmlunit.javascript.host.event.EventTarget) WebWindow(com.gargoylesoftware.htmlunit.WebWindow) AbstractJavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.AbstractJavaScriptEngine) JavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine)

Example 18 with JavaScriptEngine

use of com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine in project htmlunit by HtmlUnit.

the class Geolocation method doGetPosition.

void doGetPosition() {
    final String os = System.getProperty("os.name").toLowerCase(Locale.ROOT);
    String wifiStringString = null;
    if (os.contains("win")) {
        wifiStringString = getWifiStringWindows();
    }
    if (wifiStringString == null) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Operating System not supported: " + os);
        }
    } else {
        String url = PROVIDER_URL_;
        if (url.contains("?")) {
            url += '&';
        } else {
            url += '?';
        }
        url += "browser=firefox&sensor=true";
        url += wifiStringString;
        while (url.length() >= 1900) {
            url = url.substring(0, url.lastIndexOf("&wifi="));
        }
        if (LOG.isInfoEnabled()) {
            LOG.info("Invoking URL: " + url);
        }
        try (WebClient webClient = new WebClient(BrowserVersion.FIREFOX)) {
            final Page page = webClient.getPage(url);
            final String content = page.getWebResponse().getContentAsString();
            if (LOG.isDebugEnabled()) {
                LOG.debug("Receieved Content: " + content);
            }
            final double latitude = Double.parseDouble(getJSONValue(content, "lat"));
            final double longitude = Double.parseDouble(getJSONValue(content, "lng"));
            final double accuracy = Double.parseDouble(getJSONValue(content, "accuracy"));
            final Coordinates coordinates = new Coordinates(latitude, longitude, accuracy);
            coordinates.setPrototype(getPrototype(coordinates.getClass()));
            final Position position = new Position(coordinates);
            position.setPrototype(getPrototype(position.getClass()));
            final WebWindow ww = getWindow().getWebWindow();
            final JavaScriptEngine jsEngine = (JavaScriptEngine) ww.getWebClient().getJavaScriptEngine();
            jsEngine.callFunction((HtmlPage) ww.getEnclosedPage(), successHandler_, this, getParentScope(), new Object[] { position });
        } catch (final Exception e) {
            LOG.error("", e);
        }
    }
}
Also used : HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) Page(com.gargoylesoftware.htmlunit.Page) WebClient(com.gargoylesoftware.htmlunit.WebClient) IOException(java.io.IOException) WebWindow(com.gargoylesoftware.htmlunit.WebWindow) JavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine)

Example 19 with JavaScriptEngine

use of com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine in project htmlunit by HtmlUnit.

the class HtmlUnitRegExpProxy2Test method matchFixNeeded.

/**
 * 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();
    }
}
Also used : ContextFactory(net.sourceforge.htmlunit.corejs.javascript.ContextFactory) Context(net.sourceforge.htmlunit.corejs.javascript.Context) ScriptableObject(net.sourceforge.htmlunit.corejs.javascript.ScriptableObject) WebClient(com.gargoylesoftware.htmlunit.WebClient) JavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine) JavaScriptException(net.sourceforge.htmlunit.corejs.javascript.JavaScriptException) Test(org.junit.Test)

Example 20 with JavaScriptEngine

use of com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine in project htmlunit by HtmlUnit.

the class WebSocket method fire.

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(cx -> {
        executeEventLocally(evt);
        return null;
    });
}
Also used : JavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine)

Aggregations

JavaScriptEngine (com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine)25 WebClient (com.gargoylesoftware.htmlunit.WebClient)12 Scriptable (net.sourceforge.htmlunit.corejs.javascript.Scriptable)12 HtmlPage (com.gargoylesoftware.htmlunit.html.HtmlPage)10 ScriptableObject (net.sourceforge.htmlunit.corejs.javascript.ScriptableObject)10 JsxFunction (com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)9 Window (com.gargoylesoftware.htmlunit.javascript.host.Window)9 ContextFactory (net.sourceforge.htmlunit.corejs.javascript.ContextFactory)9 HtmlUnitScriptable (com.gargoylesoftware.htmlunit.javascript.HtmlUnitScriptable)8 IOException (java.io.IOException)8 Context (net.sourceforge.htmlunit.corejs.javascript.Context)8 WebWindow (com.gargoylesoftware.htmlunit.WebWindow)7 ContextAction (net.sourceforge.htmlunit.corejs.javascript.ContextAction)7 JsxClass (com.gargoylesoftware.htmlunit.javascript.configuration.JsxClass)6 EventTarget (com.gargoylesoftware.htmlunit.javascript.host.event.EventTarget)6 List (java.util.List)6 Function (net.sourceforge.htmlunit.corejs.javascript.Function)6 WebResponse (com.gargoylesoftware.htmlunit.WebResponse)5 PostponedAction (com.gargoylesoftware.htmlunit.javascript.PostponedAction)5 JavaScriptJob (com.gargoylesoftware.htmlunit.javascript.background.JavaScriptJob)5