Search in sources :

Example 11 with Event

use of com.gargoylesoftware.htmlunit.javascript.host.event.Event 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 12 with Event

use of com.gargoylesoftware.htmlunit.javascript.host.event.Event in project htmlunit by HtmlUnit.

the class WebClient method loadWebResponseInto.

/**
 * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
 *
 * <p>Creates a page based on the specified response and inserts it into the specified window. All page
 * initialization and event notification is handled here.</p>
 *
 * <p>Note that if the page created is an attachment page, and an {@link AttachmentHandler} has been
 * registered with this client, the page is <b>not</b> loaded into the specified window; in this case,
 * the page is loaded into a new window, and attachment handling is delegated to the registered
 * <tt>AttachmentHandler</tt>.</p>
 *
 * @param webResponse the response that will be used to create the new page
 * @param webWindow the window that the new page will be placed within
 * @param forceAttachment handle this as attachment (is set to true if the call was triggered from
 * anchor with download property set).
 * @throws IOException if an IO error occurs
 * @throws FailingHttpStatusCodeException if the server returns a failing status code AND the property
 *         {@link WebClientOptions#setThrowExceptionOnFailingStatusCode(boolean)} is set to true
 * @return the newly created page
 * @see #setAttachmentHandler(AttachmentHandler)
 */
public Page loadWebResponseInto(final WebResponse webResponse, final WebWindow webWindow, final boolean forceAttachment) throws IOException, FailingHttpStatusCodeException {
    WebAssert.notNull("webResponse", webResponse);
    WebAssert.notNull("webWindow", webWindow);
    if (webResponse.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
        return webWindow.getEnclosedPage();
    }
    if (webStartHandler_ != null && "application/x-java-jnlp-file".equals(webResponse.getContentType())) {
        webStartHandler_.handleJnlpResponse(webResponse);
        return webWindow.getEnclosedPage();
    }
    if (attachmentHandler_ != null && (forceAttachment || attachmentHandler_.isAttachment(webResponse))) {
        if (attachmentHandler_.handleAttachment(webResponse)) {
            // do not open a new window
            return webWindow.getEnclosedPage();
        }
        final WebWindow w = openWindow(null, null, webWindow);
        final Page page = pageCreator_.createPage(webResponse, w);
        attachmentHandler_.handleAttachment(page);
        return page;
    }
    final Page oldPage = webWindow.getEnclosedPage();
    if (oldPage != null) {
        // Remove the old page before create new one.
        oldPage.cleanUp();
    }
    Page newPage = null;
    FrameWindow.PageDenied pageDenied = PageDenied.NONE;
    if (windows_.contains(webWindow) || getBrowserVersion().hasFeature(WINDOW_EXECUTE_EVENTS)) {
        if (webWindow instanceof FrameWindow) {
            final String contentSecurityPolicy = webResponse.getResponseHeaderValue(HttpHeader.CONTENT_SECURIRY_POLICY);
            if (StringUtils.isNotBlank(contentSecurityPolicy) && !getBrowserVersion().hasFeature(CONTENT_SECURITY_POLICY_IGNORED)) {
                final URL origin = UrlUtils.getUrlWithoutPathRefQuery(((FrameWindow) webWindow).getEnclosingPage().getUrl());
                final URL source = UrlUtils.getUrlWithoutPathRefQuery(webResponse.getWebRequest().getUrl());
                final Policy policy = Policy.parseSerializedCSP(contentSecurityPolicy, Policy.PolicyErrorConsumer.ignored);
                if (!policy.allowsFrameAncestor(Optional.of(URI.parseURI(source.toExternalForm()).orElse(null)), Optional.of(URI.parseURI(origin.toExternalForm()).orElse(null)))) {
                    pageDenied = PageDenied.BY_CONTENT_SECURIRY_POLICY;
                    if (LOG.isWarnEnabled()) {
                        LOG.warn("Load denied by Content-Security-Policy: '" + contentSecurityPolicy + "' - " + webResponse.getWebRequest().getUrl() + "' does not permit framing.");
                    }
                }
            }
            if (pageDenied == PageDenied.NONE) {
                final String xFrameOptions = webResponse.getResponseHeaderValue(HttpHeader.X_FRAME_OPTIONS);
                if ("DENY".equalsIgnoreCase(xFrameOptions)) {
                    pageDenied = PageDenied.BY_X_FRAME_OPTIONS;
                    if (LOG.isWarnEnabled()) {
                        LOG.warn("Load denied by X-Frame-Options: DENY; - '" + webResponse.getWebRequest().getUrl() + "' does not permit framing.");
                    }
                }
            }
        }
        if (pageDenied == PageDenied.NONE) {
            newPage = pageCreator_.createPage(webResponse, webWindow);
        } else {
            try {
                final WebResponse aboutBlank = loadWebResponse(WebRequest.newAboutBlankRequest());
                newPage = pageCreator_.createPage(aboutBlank, webWindow);
                // TODO - maybe we have to attach to original request/response to the page
                ((FrameWindow) webWindow).setPageDenied(pageDenied);
            } catch (final IOException e) {
            // ignore
            }
        }
        if (windows_.contains(webWindow)) {
            fireWindowContentChanged(new WebWindowEvent(webWindow, WebWindowEvent.CHANGE, oldPage, newPage));
            // The page being loaded may already have been replaced by another page via JavaScript code.
            if (webWindow.getEnclosedPage() == newPage) {
                newPage.initialize();
                // here is a hack to handle non HTML pages
                if (isJavaScriptEnabled() && webWindow instanceof FrameWindow && !newPage.isHtmlPage()) {
                    final FrameWindow fw = (FrameWindow) webWindow;
                    final BaseFrameElement frame = fw.getFrameElement();
                    if (frame.hasEventHandlers("onload")) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Executing onload handler for " + frame);
                        }
                        final Event event = new Event(frame, Event.TYPE_LOAD);
                        ((Node) frame.getScriptableObject()).executeEventLocally(event);
                    }
                }
            }
        }
    }
    return newPage;
}
Also used : Policy(com.shapesecurity.salvation2.Policy) BaseFrameElement(com.gargoylesoftware.htmlunit.html.BaseFrameElement) DomNode(com.gargoylesoftware.htmlunit.html.DomNode) Node(com.gargoylesoftware.htmlunit.javascript.host.dom.Node) XHtmlPage(com.gargoylesoftware.htmlunit.html.XHtmlPage) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) IOException(java.io.IOException) FrameWindow(com.gargoylesoftware.htmlunit.html.FrameWindow) URL(java.net.URL) PageDenied(com.gargoylesoftware.htmlunit.html.FrameWindow.PageDenied) Event(com.gargoylesoftware.htmlunit.javascript.host.event.Event)

Example 13 with Event

use of com.gargoylesoftware.htmlunit.javascript.host.event.Event in project htmlunit by HtmlUnit.

the class ScriptElementSupport method executeEvent.

private static void executeEvent(final DomElement element, final String type) {
    final EventTarget eventTarget = element.getScriptableObject();
    final Event event = new Event(element, type);
    eventTarget.executeEventLocally(event);
}
Also used : Event(com.gargoylesoftware.htmlunit.javascript.host.event.Event) EventTarget(com.gargoylesoftware.htmlunit.javascript.host.event.EventTarget)

Example 14 with Event

use of com.gargoylesoftware.htmlunit.javascript.host.event.Event in project htmlunit by HtmlUnit.

the class Document method createEvent.

/**
 * Implementation of the {@link org.w3c.dom.events.DocumentEvent} interface's
 * {@link org.w3c.dom.events.DocumentEvent#createEvent(String)} method. The method creates an
 * uninitialized event of the specified type.
 *
 * @see <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-DocumentEvent">DocumentEvent</a>
 * @param eventType the event type to create
 * @return an event object for the specified type
 * @throws DOMException if the event type is not supported (will have a type of
 *         DOMException.NOT_SUPPORTED_ERR)
 */
@JsxFunction
public Event createEvent(final String eventType) throws DOMException {
    Class<? extends Event> clazz = SUPPORTED_DOM2_EVENT_TYPE_MAP.get(eventType);
    if (clazz == null) {
        clazz = SUPPORTED_DOM3_EVENT_TYPE_MAP.get(eventType);
        if (CloseEvent.class == clazz && getBrowserVersion().hasFeature(EVENT_ONCLOSE_DOCUMENT_CREATE_NOT_SUPPORTED)) {
            clazz = null;
        }
    }
    if (clazz == null && ("Events".equals(eventType) || "HashChangeEvent".equals(eventType) && getBrowserVersion().hasFeature(EVENT_TYPE_HASHCHANGEEVENT) || "BeforeUnloadEvent".equals(eventType) && getBrowserVersion().hasFeature(EVENT_TYPE_BEFOREUNLOADEVENT) || "MouseWheelEvent".equals(eventType) && getBrowserVersion().hasFeature(EVENT_TYPE_MOUSEWHEELEVENT) || "PointerEvent".equals(eventType) && getBrowserVersion().hasFeature(EVENT_TYPE_POINTEREVENT) || "PopStateEvent".equals(eventType) || "ProgressEvent".equals(eventType) && getBrowserVersion().hasFeature(EVENT_TYPE_PROGRESSEVENT) || "FocusEvent".equals(eventType) || "WheelEvent".equals(eventType) && getBrowserVersion().hasFeature(EVENT_TYPE_WHEELEVENT))) {
        clazz = SUPPORTED_VENDOR_EVENT_TYPE_MAP.get(eventType);
        if (PopStateEvent.class == clazz && getBrowserVersion().hasFeature(EVENT_ONPOPSTATE_DOCUMENT_CREATE_NOT_SUPPORTED)) {
            clazz = null;
        }
    }
    if (clazz == null) {
        Context.throwAsScriptRuntimeEx(new DOMException(DOMException.NOT_SUPPORTED_ERR, "Event Type is not supported: " + eventType));
        // to stop eclipse warning
        return null;
    }
    try {
        final Event event = clazz.newInstance();
        event.setParentScope(getWindow());
        event.setPrototype(getPrototype(clazz));
        event.eventCreated();
        return event;
    } catch (final InstantiationException | IllegalAccessException e) {
        throw Context.reportRuntimeError("Failed to instantiate event: class ='" + clazz.getName() + "' for event type of '" + eventType + "': " + e.getMessage());
    }
}
Also used : PopStateEvent(com.gargoylesoftware.htmlunit.javascript.host.event.PopStateEvent) CloseEvent(com.gargoylesoftware.htmlunit.javascript.host.event.CloseEvent) DOMException(org.w3c.dom.DOMException) CustomEvent(com.gargoylesoftware.htmlunit.javascript.host.event.CustomEvent) MouseEvent(com.gargoylesoftware.htmlunit.javascript.host.event.MouseEvent) PopStateEvent(com.gargoylesoftware.htmlunit.javascript.host.event.PopStateEvent) SVGZoomEvent(com.gargoylesoftware.htmlunit.javascript.host.event.SVGZoomEvent) ProgressEvent(com.gargoylesoftware.htmlunit.javascript.host.event.ProgressEvent) FocusEvent(com.gargoylesoftware.htmlunit.javascript.host.event.FocusEvent) CompositionEvent(com.gargoylesoftware.htmlunit.javascript.host.event.CompositionEvent) WheelEvent(com.gargoylesoftware.htmlunit.javascript.host.event.WheelEvent) KeyboardEvent(com.gargoylesoftware.htmlunit.javascript.host.event.KeyboardEvent) PointerEvent(com.gargoylesoftware.htmlunit.javascript.host.event.PointerEvent) HtmlAttributeChangeEvent(com.gargoylesoftware.htmlunit.html.HtmlAttributeChangeEvent) TextEvent(com.gargoylesoftware.htmlunit.javascript.host.event.TextEvent) CloseEvent(com.gargoylesoftware.htmlunit.javascript.host.event.CloseEvent) MouseWheelEvent(com.gargoylesoftware.htmlunit.javascript.host.event.MouseWheelEvent) HashChangeEvent(com.gargoylesoftware.htmlunit.javascript.host.event.HashChangeEvent) MutationEvent(com.gargoylesoftware.htmlunit.javascript.host.event.MutationEvent) UIEvent(com.gargoylesoftware.htmlunit.javascript.host.event.UIEvent) Event(com.gargoylesoftware.htmlunit.javascript.host.event.Event) DragEvent(com.gargoylesoftware.htmlunit.javascript.host.event.DragEvent) BeforeUnloadEvent(com.gargoylesoftware.htmlunit.javascript.host.event.BeforeUnloadEvent) MessageEvent(com.gargoylesoftware.htmlunit.javascript.host.event.MessageEvent) JsxFunction(com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)

Example 15 with Event

use of com.gargoylesoftware.htmlunit.javascript.host.event.Event in project jenkins by jenkinsci.

the class ProjectTest method testGetScmCheckoutRetryCount.

@Test
public void testGetScmCheckoutRetryCount() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject("project");
    assertEquals("Scm retry count should be default.", j.jenkins.getScmCheckoutRetryCount(), p.getScmCheckoutRetryCount());
    j.jenkins.setScmCheckoutRetryCount(6);
    assertEquals("Scm retry count should be the same as global scm retry count.", 6, p.getScmCheckoutRetryCount());
    HtmlForm form = j.createWebClient().goTo(p.getUrl() + "/configure").getFormByName("config");
    ((HtmlElement) form.getByXPath("//div[@class='advancedLink']//button").get(0)).click();
    // required due to the new default behavior of click
    form.getInputByName("hasCustomScmCheckoutRetryCount").click(new Event(), false, false, false, true);
    form.getInputByName("scmCheckoutRetryCount").setValueAttribute("7");
    j.submit(form);
    assertEquals("Scm retry count was set.", 7, p.getScmCheckoutRetryCount());
}
Also used : HtmlForm(com.gargoylesoftware.htmlunit.html.HtmlForm) HtmlElement(com.gargoylesoftware.htmlunit.html.HtmlElement) Event(com.gargoylesoftware.htmlunit.javascript.host.event.Event) Test(org.junit.Test)

Aggregations

Event (com.gargoylesoftware.htmlunit.javascript.host.event.Event)25 JsxFunction (com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)11 MouseEvent (com.gargoylesoftware.htmlunit.javascript.host.event.MouseEvent)9 MessageEvent (com.gargoylesoftware.htmlunit.javascript.host.event.MessageEvent)8 BrowserVersion (com.gargoylesoftware.htmlunit.BrowserVersion)6 WebClient (com.gargoylesoftware.htmlunit.WebClient)6 HtmlAttributeChangeEvent (com.gargoylesoftware.htmlunit.html.HtmlAttributeChangeEvent)6 IOException (java.io.IOException)6 ScriptResult (com.gargoylesoftware.htmlunit.ScriptResult)5 EventTarget (com.gargoylesoftware.htmlunit.javascript.host.event.EventTarget)5 HTMLElement (com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement)5 WebWindow (com.gargoylesoftware.htmlunit.WebWindow)4 HtmlPage (com.gargoylesoftware.htmlunit.html.HtmlPage)4 JavaScriptEngine (com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine)4 URL (java.net.URL)4 Page (com.gargoylesoftware.htmlunit.Page)3 SgmlPage (com.gargoylesoftware.htmlunit.SgmlPage)3 TopLevelWindow (com.gargoylesoftware.htmlunit.TopLevelWindow)3 HtmlUnitScriptable (com.gargoylesoftware.htmlunit.javascript.HtmlUnitScriptable)3 JsxClass (com.gargoylesoftware.htmlunit.javascript.configuration.JsxClass)3