Search in sources :

Example 1 with JavaScriptEngine

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

the class HtmlPage method executeJavaScriptFunction.

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);
}
Also used : ScriptResult(com.gargoylesoftware.htmlunit.ScriptResult) ScriptableObject(net.sourceforge.htmlunit.corejs.javascript.ScriptableObject) AbstractJavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.AbstractJavaScriptEngine) JavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine)

Example 2 with JavaScriptEngine

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

the class NamedAttrNodeMapImpl method fireEvent.

/**
 * <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;
}
Also used : ScriptResult(com.gargoylesoftware.htmlunit.ScriptResult) HtmlUnitContextFactory(com.gargoylesoftware.htmlunit.javascript.HtmlUnitContextFactory) WebClient(com.gargoylesoftware.htmlunit.WebClient) EventTarget(com.gargoylesoftware.htmlunit.javascript.host.event.EventTarget) AbstractJavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.AbstractJavaScriptEngine) JavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine)

Example 3 with JavaScriptEngine

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

the class XMLHTTPRequest method setState.

/**
 * 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.");
        }
    }
}
Also used : Scriptable(net.sourceforge.htmlunit.corejs.javascript.Scriptable) JavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine)

Example 4 with JavaScriptEngine

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

the class XMLHTTPRequest method send.

/**
 * Sends an HTTP request to the server and receives a response.
 * @param body the body of the message being sent with the request.
 */
@JsxFunction
public void send(final Object body) {
    if (webRequest_ == null) {
        setState(STATE_DONE, Context.getCurrentContext());
        return;
    }
    if (sent_) {
        throw Context.reportRuntimeError("Unspecified error (request already sent).");
    }
    sent_ = true;
    prepareRequest(body);
    // quite strange but IE seems to fire state loading twice
    setState(STATE_OPENED, Context.getCurrentContext());
    final Window w = getWindow();
    final WebClient client = w.getWebWindow().getWebClient();
    final AjaxController ajaxController = client.getAjaxController();
    final HtmlPage page = (HtmlPage) w.getWebWindow().getEnclosedPage();
    final boolean synchron = ajaxController.processSynchron(page, webRequest_, async_);
    if (synchron) {
        doSend(Context.getCurrentContext());
    } else {
        // Create and start a thread in which to execute the request.
        final ContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
        final ContextAction<Object> action = cx -> {
            // KEY_STARTING_SCOPE maintains a stack of scopes
            @SuppressWarnings("unchecked") Deque<Scriptable> stack = (Deque<Scriptable>) cx.getThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE);
            if (null == stack) {
                stack = new ArrayDeque<>();
                cx.putThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE, stack);
            }
            stack.push(w);
            try {
                doSend(cx);
            } finally {
                stack.pop();
            }
            return null;
        };
        final JavaScriptJob job = BackgroundJavaScriptFactory.theFactory().createJavascriptXMLHttpRequestJob(cf, action);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Starting XMLHTTPRequest thread for asynchronous request");
        }
        jobID_ = w.getWebWindow().getJobManager().addJob(job, page);
    }
}
Also used : Window(com.gargoylesoftware.htmlunit.javascript.host.Window) Arrays(java.util.Arrays) URL(java.net.URL) ArrayUtils(org.apache.commons.lang3.ArrayUtils) Deque(java.util.Deque) NameValuePair(com.gargoylesoftware.htmlunit.util.NameValuePair) StringUtils(org.apache.commons.lang3.StringUtils) FormEncodingType(com.gargoylesoftware.htmlunit.FormEncodingType) BackgroundJavaScriptFactory(com.gargoylesoftware.htmlunit.javascript.background.BackgroundJavaScriptFactory) Charset(java.nio.charset.Charset) ContextAction(net.sourceforge.htmlunit.corejs.javascript.ContextAction) Locale(java.util.Locale) FormData(com.gargoylesoftware.htmlunit.javascript.host.xml.FormData) HttpMethod(com.gargoylesoftware.htmlunit.HttpMethod) JavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine) MimeType(com.gargoylesoftware.htmlunit.util.MimeType) Context(net.sourceforge.htmlunit.corejs.javascript.Context) XmlPage(com.gargoylesoftware.htmlunit.xml.XmlPage) WebRequest(com.gargoylesoftware.htmlunit.WebRequest) Scriptable(net.sourceforge.htmlunit.corejs.javascript.Scriptable) JsxSetter(com.gargoylesoftware.htmlunit.javascript.configuration.JsxSetter) Window(com.gargoylesoftware.htmlunit.javascript.host.Window) ScriptRuntime(net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime) MalformedURLException(java.net.MalformedURLException) UTF_8(java.nio.charset.StandardCharsets.UTF_8) HttpHeader(com.gargoylesoftware.htmlunit.HttpHeader) Collection(java.util.Collection) IOException(java.io.IOException) JavaScriptJob(com.gargoylesoftware.htmlunit.javascript.background.JavaScriptJob) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) WebResponse(com.gargoylesoftware.htmlunit.WebResponse) JsxGetter(com.gargoylesoftware.htmlunit.javascript.configuration.JsxGetter) JsxFunction(com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) JsxClass(com.gargoylesoftware.htmlunit.javascript.configuration.JsxClass) List(java.util.List) ContextFactory(net.sourceforge.htmlunit.corejs.javascript.ContextFactory) JsxConstructor(com.gargoylesoftware.htmlunit.javascript.configuration.JsxConstructor) IE(com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.IE) Entry(java.util.Map.Entry) Log(org.apache.commons.logging.Log) WebClient(com.gargoylesoftware.htmlunit.WebClient) LogFactory(org.apache.commons.logging.LogFactory) AjaxController(com.gargoylesoftware.htmlunit.AjaxController) Undefined(net.sourceforge.htmlunit.corejs.javascript.Undefined) ArrayDeque(java.util.ArrayDeque) Function(net.sourceforge.htmlunit.corejs.javascript.Function) Collections(java.util.Collections) InputStream(java.io.InputStream) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) Scriptable(net.sourceforge.htmlunit.corejs.javascript.Scriptable) WebClient(com.gargoylesoftware.htmlunit.WebClient) Deque(java.util.Deque) ArrayDeque(java.util.ArrayDeque) ArrayDeque(java.util.ArrayDeque) ContextFactory(net.sourceforge.htmlunit.corejs.javascript.ContextFactory) JavaScriptJob(com.gargoylesoftware.htmlunit.javascript.background.JavaScriptJob) AjaxController(com.gargoylesoftware.htmlunit.AjaxController) JavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine) JsxFunction(com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)

Example 5 with JavaScriptEngine

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

the class HTMLCollectionFrames method postMessage.

/**
 * Posts a message.
 * @param message the object passed to the window
 * @param targetOrigin the origin this window must be for the event to be dispatched
 * @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 String targetOrigin, final Object transfer) {
    final WebWindow webWindow = getWebWindow();
    final Page page = webWindow.getEnclosedPage();
    final URL currentURL = page.getUrl();
    if (!"*".equals(targetOrigin) && !"/".equals(targetOrigin)) {
        final URL targetURL;
        try {
            targetURL = new URL(targetOrigin);
        } catch (final Exception e) {
            throw Context.throwAsScriptRuntimeEx(new Exception("SyntaxError: Failed to execute 'postMessage' on 'Window': Invalid target origin '" + targetOrigin + "' was specified (reason: " + e.getMessage() + "."));
        }
        if (getPort(targetURL) != getPort(currentURL)) {
            return;
        }
        if (!targetURL.getHost().equals(currentURL.getHost())) {
            return;
        }
        if (!targetURL.getProtocol().equals(currentURL.getProtocol())) {
            return;
        }
    }
    final MessageEvent event = new MessageEvent();
    final String origin = currentURL.getProtocol() + "://" + currentURL.getHost() + ':' + currentURL.getPort();
    event.initMessageEvent(Event.TYPE_MESSAGE, false, false, message, origin, "", this, transfer);
    event.setParentScope(this);
    event.setPrototype(getPrototype(event.getClass()));
    final JavaScriptEngine jsEngine = (JavaScriptEngine) webWindow.getWebClient().getJavaScriptEngine();
    final PostponedAction action = new PostponedAction(page, "Window.postMessage") {

        @Override
        public void execute() throws Exception {
            final ContextAction<Object> contextAction = cx -> dispatchEvent(event);
            final ContextFactory cf = jsEngine.getContextFactory();
            cf.call(contextAction);
        }
    };
    jsEngine.addPostponedAction(action);
}
Also used : DomElement(com.gargoylesoftware.htmlunit.html.DomElement) WebWindow(com.gargoylesoftware.htmlunit.WebWindow) DialogWindow(com.gargoylesoftware.htmlunit.DialogWindow) HtmlMap(com.gargoylesoftware.htmlunit.html.HtmlMap) JS_WINDOW_SELECTION_NULL_IF_INVISIBLE(com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_WINDOW_SELECTION_NULL_IF_INVISIBLE) FF(com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.FF) MediaQueryList(com.gargoylesoftware.htmlunit.javascript.host.css.MediaQueryList) EDGE(com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.EDGE) StringUtils(org.apache.commons.lang3.StringUtils) JsxConstant(com.gargoylesoftware.htmlunit.javascript.configuration.JsxConstant) MouseEvent(com.gargoylesoftware.htmlunit.javascript.host.event.MouseEvent) BaseFrameElement(com.gargoylesoftware.htmlunit.html.BaseFrameElement) ContextAction(net.sourceforge.htmlunit.corejs.javascript.ContextAction) Map(java.util.Map) JS_WINDOW_CHANGE_OPENER_ONLY_WINDOW_OBJECT(com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_WINDOW_CHANGE_OPENER_ONLY_WINDOW_OBJECT) Scriptable(net.sourceforge.htmlunit.corejs.javascript.Scriptable) JsxSetter(com.gargoylesoftware.htmlunit.javascript.configuration.JsxSetter) HTMLCollection(com.gargoylesoftware.htmlunit.javascript.host.html.HTMLCollection) EnumMap(java.util.EnumMap) DomNode(com.gargoylesoftware.htmlunit.html.DomNode) JsxGetter(com.gargoylesoftware.htmlunit.javascript.configuration.JsxGetter) SpeechSynthesis(com.gargoylesoftware.htmlunit.javascript.host.speech.SpeechSynthesis) JS_WINDOW_TOP_WRITABLE(com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_WINDOW_TOP_WRITABLE) HtmlElement(com.gargoylesoftware.htmlunit.html.HtmlElement) HtmlInput(com.gargoylesoftware.htmlunit.html.HtmlInput) LogFactory(org.apache.commons.logging.LogFactory) AlertHandler(com.gargoylesoftware.htmlunit.AlertHandler) HtmlAnchor(com.gargoylesoftware.htmlunit.html.HtmlAnchor) HtmlEmbed(com.gargoylesoftware.htmlunit.html.HtmlEmbed) ScriptableObject(net.sourceforge.htmlunit.corejs.javascript.ScriptableObject) PromptHandler(com.gargoylesoftware.htmlunit.PromptHandler) UrlUtils(com.gargoylesoftware.htmlunit.util.UrlUtils) ArrayList(java.util.ArrayList) JavaScriptException(net.sourceforge.htmlunit.corejs.javascript.JavaScriptException) XmlPage(com.gargoylesoftware.htmlunit.xml.XmlPage) IOException(java.io.IOException) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) JsxFunction(com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction) CSS2Properties(com.gargoylesoftware.htmlunit.javascript.host.css.CSS2Properties) JsxClass(com.gargoylesoftware.htmlunit.javascript.configuration.JsxClass) Performance(com.gargoylesoftware.htmlunit.javascript.host.performance.Performance) IE(com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.IE) WebClient(com.gargoylesoftware.htmlunit.WebClient) JS_WINDOW_FRAMES_ACCESSIBLE_BY_ID(com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_WINDOW_FRAMES_ACCESSIBLE_BY_ID) ElementNotFoundException(com.gargoylesoftware.htmlunit.ElementNotFoundException) StyleMedia(com.gargoylesoftware.htmlunit.javascript.host.css.StyleMedia) ScriptResult(com.gargoylesoftware.htmlunit.ScriptResult) HtmlImage(com.gargoylesoftware.htmlunit.html.HtmlImage) URL(java.net.URL) ObjectInputStream(java.io.ObjectInputStream) HtmlTextArea(com.gargoylesoftware.htmlunit.html.HtmlTextArea) HtmlObject(com.gargoylesoftware.htmlunit.html.HtmlObject) HtmlAttributeChangeEvent(com.gargoylesoftware.htmlunit.html.HtmlAttributeChangeEvent) JS_WINDOW_FRAME_BY_ID_RETURNS_WINDOW(com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_WINDOW_FRAME_BY_ID_RETURNS_WINDOW) DataTransfer(com.gargoylesoftware.htmlunit.javascript.host.html.DataTransfer) ScriptException(com.gargoylesoftware.htmlunit.ScriptException) FF_ESR(com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.FF_ESR) Selection(com.gargoylesoftware.htmlunit.javascript.host.dom.Selection) HtmlForm(com.gargoylesoftware.htmlunit.html.HtmlForm) StatusHandler(com.gargoylesoftware.htmlunit.StatusHandler) ConfirmHandler(com.gargoylesoftware.htmlunit.ConfirmHandler) Crypto(com.gargoylesoftware.htmlunit.javascript.host.crypto.Crypto) List(java.util.List) DocumentProxy(com.gargoylesoftware.htmlunit.javascript.host.html.DocumentProxy) ContextFactory(net.sourceforge.htmlunit.corejs.javascript.ContextFactory) Undefined(net.sourceforge.htmlunit.corejs.javascript.Undefined) Function(net.sourceforge.htmlunit.corejs.javascript.Function) Page(com.gargoylesoftware.htmlunit.Page) EventTarget(com.gargoylesoftware.htmlunit.javascript.host.event.EventTarget) HTMLDocument(com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument) HtmlUnitScriptable(com.gargoylesoftware.htmlunit.javascript.HtmlUnitScriptable) HashMap(java.util.HashMap) WebWindowNotFoundException(com.gargoylesoftware.htmlunit.WebWindowNotFoundException) HtmlFrame(com.gargoylesoftware.htmlunit.html.HtmlFrame) JS_WINDOW_FORMFIELDS_ACCESSIBLE_BY_NAME(com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_WINDOW_FORMFIELDS_ACCESSIBLE_BY_NAME) TopLevelWindow(com.gargoylesoftware.htmlunit.TopLevelWindow) BrowserVersion(com.gargoylesoftware.htmlunit.BrowserVersion) HtmlSelect(com.gargoylesoftware.htmlunit.html.HtmlSelect) SgmlPage(com.gargoylesoftware.htmlunit.SgmlPage) EcmaError(net.sourceforge.htmlunit.corejs.javascript.EcmaError) Event(com.gargoylesoftware.htmlunit.javascript.host.event.Event) JavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine) Context(net.sourceforge.htmlunit.corejs.javascript.Context) FrameWindow(com.gargoylesoftware.htmlunit.html.FrameWindow) HtmlButton(com.gargoylesoftware.htmlunit.html.HtmlButton) XMLDocument(com.gargoylesoftware.htmlunit.javascript.host.xml.XMLDocument) ScriptRuntime(net.sourceforge.htmlunit.corejs.javascript.ScriptRuntime) MalformedURLException(java.net.MalformedURLException) Type(com.gargoylesoftware.htmlunit.StorageHolder.Type) CHROME(com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.CHROME) PostponedAction(com.gargoylesoftware.htmlunit.javascript.PostponedAction) WebAssert(com.gargoylesoftware.htmlunit.WebAssert) JsxConstructor(com.gargoylesoftware.htmlunit.javascript.configuration.JsxConstructor) Document(com.gargoylesoftware.htmlunit.javascript.host.dom.Document) HTMLElement(com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement) Log(org.apache.commons.logging.Log) MessageEvent(com.gargoylesoftware.htmlunit.javascript.host.event.MessageEvent) ContextFactory(net.sourceforge.htmlunit.corejs.javascript.ContextFactory) MessageEvent(com.gargoylesoftware.htmlunit.javascript.host.event.MessageEvent) XmlPage(com.gargoylesoftware.htmlunit.xml.XmlPage) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) Page(com.gargoylesoftware.htmlunit.Page) SgmlPage(com.gargoylesoftware.htmlunit.SgmlPage) PostponedAction(com.gargoylesoftware.htmlunit.javascript.PostponedAction) ScriptableObject(net.sourceforge.htmlunit.corejs.javascript.ScriptableObject) HtmlObject(com.gargoylesoftware.htmlunit.html.HtmlObject) URL(java.net.URL) JavaScriptException(net.sourceforge.htmlunit.corejs.javascript.JavaScriptException) IOException(java.io.IOException) ElementNotFoundException(com.gargoylesoftware.htmlunit.ElementNotFoundException) ScriptException(com.gargoylesoftware.htmlunit.ScriptException) WebWindowNotFoundException(com.gargoylesoftware.htmlunit.WebWindowNotFoundException) MalformedURLException(java.net.MalformedURLException) WebWindow(com.gargoylesoftware.htmlunit.WebWindow) JavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine) JsxFunction(com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)

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