Search in sources :

Example 1 with ContextAction

use of net.sourceforge.htmlunit.corejs.javascript.ContextAction 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 2 with ContextAction

use of net.sourceforge.htmlunit.corejs.javascript.ContextAction 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)

Example 3 with ContextAction

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

the class WorkerJob method postMessage.

/**
 * 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_, Undefined.instance);
    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<Object> action = cx -> {
        worker_.getEventListenersContainer().executeCapturingListeners(event, null);
        final Object[] args = { event };
        worker_.getEventListenersContainer().executeBubblingListeners(event, args);
        return null;
    };
    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);
}
Also used : AbstractJavaScriptConfiguration(com.gargoylesoftware.htmlunit.javascript.configuration.AbstractJavaScriptConfiguration) WindowOrWorkerGlobalScopeMixin(com.gargoylesoftware.htmlunit.javascript.host.WindowOrWorkerGlobalScopeMixin) URL(java.net.URL) Script(net.sourceforge.htmlunit.corejs.javascript.Script) HtmlUnitScriptable(com.gargoylesoftware.htmlunit.javascript.HtmlUnitScriptable) FF(com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.FF) EDGE(com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.EDGE) ClassConfiguration(com.gargoylesoftware.htmlunit.javascript.configuration.ClassConfiguration) BrowserVersion(com.gargoylesoftware.htmlunit.BrowserVersion) ContextAction(net.sourceforge.htmlunit.corejs.javascript.ContextAction) FF_ESR(com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.FF_ESR) Event(com.gargoylesoftware.htmlunit.javascript.host.event.Event) JavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine) MimeType(com.gargoylesoftware.htmlunit.util.MimeType) Context(net.sourceforge.htmlunit.corejs.javascript.Context) 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) CHROME(com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.CHROME) 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) JsxClass(com.gargoylesoftware.htmlunit.javascript.configuration.JsxClass) List(java.util.List) ContextFactory(net.sourceforge.htmlunit.corejs.javascript.ContextFactory) IE(com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.IE) WindowOrWorkerGlobalScope(com.gargoylesoftware.htmlunit.javascript.host.WindowOrWorkerGlobalScope) Log(org.apache.commons.logging.Log) WebClient(com.gargoylesoftware.htmlunit.WebClient) LogFactory(org.apache.commons.logging.LogFactory) Undefined(net.sourceforge.htmlunit.corejs.javascript.Undefined) Function(net.sourceforge.htmlunit.corejs.javascript.Function) JS_WORKER_IMPORT_SCRIPTS_ACCEPTS_ALL(com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_WORKER_IMPORT_SCRIPTS_ACCEPTS_ALL) MessageEvent(com.gargoylesoftware.htmlunit.javascript.host.event.MessageEvent) EventTarget(com.gargoylesoftware.htmlunit.javascript.host.event.EventTarget) BasicJavaScriptJob(com.gargoylesoftware.htmlunit.javascript.background.BasicJavaScriptJob) ContextFactory(net.sourceforge.htmlunit.corejs.javascript.ContextFactory) JavaScriptJob(com.gargoylesoftware.htmlunit.javascript.background.JavaScriptJob) BasicJavaScriptJob(com.gargoylesoftware.htmlunit.javascript.background.BasicJavaScriptJob) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) MessageEvent(com.gargoylesoftware.htmlunit.javascript.host.event.MessageEvent) JavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine) JsxFunction(com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)

Example 4 with ContextAction

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

the class WorkerJob method messagePosted.

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 = 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);
}
Also used : AbstractJavaScriptConfiguration(com.gargoylesoftware.htmlunit.javascript.configuration.AbstractJavaScriptConfiguration) WindowOrWorkerGlobalScopeMixin(com.gargoylesoftware.htmlunit.javascript.host.WindowOrWorkerGlobalScopeMixin) URL(java.net.URL) Script(net.sourceforge.htmlunit.corejs.javascript.Script) HtmlUnitScriptable(com.gargoylesoftware.htmlunit.javascript.HtmlUnitScriptable) FF(com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.FF) EDGE(com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.EDGE) ClassConfiguration(com.gargoylesoftware.htmlunit.javascript.configuration.ClassConfiguration) BrowserVersion(com.gargoylesoftware.htmlunit.BrowserVersion) ContextAction(net.sourceforge.htmlunit.corejs.javascript.ContextAction) FF_ESR(com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.FF_ESR) Event(com.gargoylesoftware.htmlunit.javascript.host.event.Event) JavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine) MimeType(com.gargoylesoftware.htmlunit.util.MimeType) Context(net.sourceforge.htmlunit.corejs.javascript.Context) 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) CHROME(com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.CHROME) 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) JsxClass(com.gargoylesoftware.htmlunit.javascript.configuration.JsxClass) List(java.util.List) ContextFactory(net.sourceforge.htmlunit.corejs.javascript.ContextFactory) IE(com.gargoylesoftware.htmlunit.javascript.configuration.SupportedBrowser.IE) WindowOrWorkerGlobalScope(com.gargoylesoftware.htmlunit.javascript.host.WindowOrWorkerGlobalScope) Log(org.apache.commons.logging.Log) WebClient(com.gargoylesoftware.htmlunit.WebClient) LogFactory(org.apache.commons.logging.LogFactory) Undefined(net.sourceforge.htmlunit.corejs.javascript.Undefined) Function(net.sourceforge.htmlunit.corejs.javascript.Function) JS_WORKER_IMPORT_SCRIPTS_ACCEPTS_ALL(com.gargoylesoftware.htmlunit.BrowserVersionFeatures.JS_WORKER_IMPORT_SCRIPTS_ACCEPTS_ALL) MessageEvent(com.gargoylesoftware.htmlunit.javascript.host.event.MessageEvent) EventTarget(com.gargoylesoftware.htmlunit.javascript.host.event.EventTarget) BasicJavaScriptJob(com.gargoylesoftware.htmlunit.javascript.background.BasicJavaScriptJob) ContextFactory(net.sourceforge.htmlunit.corejs.javascript.ContextFactory) JavaScriptJob(com.gargoylesoftware.htmlunit.javascript.background.JavaScriptJob) BasicJavaScriptJob(com.gargoylesoftware.htmlunit.javascript.background.BasicJavaScriptJob) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) MessageEvent(com.gargoylesoftware.htmlunit.javascript.host.event.MessageEvent) JavaScriptEngine(com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine)

Example 5 with ContextAction

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

the class DebuggingWebConnection method uncompressJavaScript.

/**
 * Tries to uncompress the JavaScript code in the provided response.
 * @param response the response to uncompress
 * @return a new response with uncompressed JavaScript code or the original response in case of failure
 */
protected WebResponse uncompressJavaScript(final WebResponse response) {
    final WebRequest request = response.getWebRequest();
    final String scriptName = request.getUrl().toString();
    final String scriptSource = response.getContentAsString();
    // skip if it is already formatted? => TODO
    final ContextFactory factory = new ContextFactory();
    final ContextAction<Object> action = cx -> {
        cx.setOptimizationLevel(-1);
        final Script script = cx.compileString(scriptSource, scriptName, 0, null);
        return cx.decompileScript(script, 4);
    };
    try {
        final String decompileScript = (String) factory.call(action);
        final List<NameValuePair> responseHeaders = new ArrayList<>(response.getResponseHeaders());
        for (int i = responseHeaders.size() - 1; i >= 0; i--) {
            if ("content-encoding".equalsIgnoreCase(responseHeaders.get(i).getName())) {
                responseHeaders.remove(i);
            }
        }
        final WebResponseData wrd = new WebResponseData(decompileScript.getBytes(), response.getStatusCode(), response.getStatusMessage(), responseHeaders);
        return new WebResponse(wrd, response.getWebRequest().getUrl(), response.getWebRequest().getHttpMethod(), response.getLoadTime());
    } catch (final Exception e) {
        LOG.warn("Failed to decompress JavaScript response. Delivering as it.", e);
    }
    return response;
}
Also used : URL(java.net.URL) Script(net.sourceforge.htmlunit.corejs.javascript.Script) StringUtils(org.apache.commons.lang3.StringUtils) FormEncodingType(com.gargoylesoftware.htmlunit.FormEncodingType) ArrayList(java.util.ArrayList) WebConnection(com.gargoylesoftware.htmlunit.WebConnection) ISO_8859_1(java.nio.charset.StandardCharsets.ISO_8859_1) ContextAction(net.sourceforge.htmlunit.corejs.javascript.ContextAction) HttpMethod(com.gargoylesoftware.htmlunit.HttpMethod) OutputStream(java.io.OutputStream) WebRequest(com.gargoylesoftware.htmlunit.WebRequest) Files(java.nio.file.Files) BufferedWriter(java.io.BufferedWriter) StandardOpenOption(java.nio.file.StandardOpenOption) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) EOFException(java.io.EOFException) WebResponse(com.gargoylesoftware.htmlunit.WebResponse) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) WebResponseData(com.gargoylesoftware.htmlunit.WebResponseData) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) ContextFactory(net.sourceforge.htmlunit.corejs.javascript.ContextFactory) Log(org.apache.commons.logging.Log) Pattern(java.util.regex.Pattern) LogFactory(org.apache.commons.logging.LogFactory) InputStream(java.io.InputStream) Script(net.sourceforge.htmlunit.corejs.javascript.Script) WebResponse(com.gargoylesoftware.htmlunit.WebResponse) ArrayList(java.util.ArrayList) IOException(java.io.IOException) EOFException(java.io.EOFException) ContextFactory(net.sourceforge.htmlunit.corejs.javascript.ContextFactory) WebRequest(com.gargoylesoftware.htmlunit.WebRequest) WebResponseData(com.gargoylesoftware.htmlunit.WebResponseData)

Aggregations

ContextAction (net.sourceforge.htmlunit.corejs.javascript.ContextAction)44 Context (net.sourceforge.htmlunit.corejs.javascript.Context)42 Scriptable (net.sourceforge.htmlunit.corejs.javascript.Scriptable)40 ScriptableObject (net.sourceforge.htmlunit.corejs.javascript.ScriptableObject)16 Test (org.junit.jupiter.api.Test)15 ContextFactory (net.sourceforge.htmlunit.corejs.javascript.ContextFactory)13 WebClient (com.gargoylesoftware.htmlunit.WebClient)7 JavaScriptEngine (com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine)7 JsxFunction (com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)7 List (java.util.List)7 Function (net.sourceforge.htmlunit.corejs.javascript.Function)7 HtmlPage (com.gargoylesoftware.htmlunit.html.HtmlPage)6 JsxClass (com.gargoylesoftware.htmlunit.javascript.configuration.JsxClass)6 Script (net.sourceforge.htmlunit.corejs.javascript.Script)6 WebRequest (com.gargoylesoftware.htmlunit.WebRequest)5 WebResponse (com.gargoylesoftware.htmlunit.WebResponse)5 HtmlUnitScriptable (com.gargoylesoftware.htmlunit.javascript.HtmlUnitScriptable)5 JavaScriptJob (com.gargoylesoftware.htmlunit.javascript.background.JavaScriptJob)5 JsxGetter (com.gargoylesoftware.htmlunit.javascript.configuration.JsxGetter)5 JsxSetter (com.gargoylesoftware.htmlunit.javascript.configuration.JsxSetter)5