Search in sources :

Example 16 with Event

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

the class NamedAttrNodeMapImpl method doMouseEvent.

/**
 * Simulates the specified mouse event, returning the page which this element's window contains after the event.
 * The returned page may or may not be the same as the original page, depending on JavaScript event handlers, etc.
 *
 * @param eventType the mouse event type to simulate
 * @param shiftKey {@code true} if SHIFT is pressed during the mouse event
 * @param ctrlKey {@code true} if CTRL is pressed during the mouse event
 * @param altKey {@code true} if ALT is pressed during the mouse event
 * @param button the button code, must be {@link MouseEvent#BUTTON_LEFT}, {@link MouseEvent#BUTTON_MIDDLE}
 *        or {@link MouseEvent#BUTTON_RIGHT}
 * @return the page which this element's window contains after the event
 */
private Page doMouseEvent(final String eventType, final boolean shiftKey, final boolean ctrlKey, final boolean altKey, final int button) {
    final SgmlPage page = getPage();
    if (!page.getWebClient().isJavaScriptEnabled()) {
        return page;
    }
    final ScriptResult scriptResult;
    final Event event;
    if (MouseEvent.TYPE_CONTEXT_MENU.equals(eventType) && getPage().getWebClient().getBrowserVersion().hasFeature(EVENT_ONCLICK_USES_POINTEREVENT)) {
        event = new PointerEvent(this, eventType, shiftKey, ctrlKey, altKey, button, 0);
    } else {
        event = new MouseEvent(this, eventType, shiftKey, ctrlKey, altKey, button);
    }
    scriptResult = fireEvent(event);
    final Page currentPage;
    if (scriptResult == null) {
        currentPage = page;
    } else {
        currentPage = page.getWebClient().getCurrentWindow().getEnclosedPage();
    }
    final boolean mouseOver = !MouseEvent.TYPE_MOUSE_OUT.equals(eventType);
    if (mouseOver_ != mouseOver) {
        mouseOver_ = mouseOver;
        page.clearComputedStyles();
    }
    return currentPage;
}
Also used : ScriptResult(com.gargoylesoftware.htmlunit.ScriptResult) PointerEvent(com.gargoylesoftware.htmlunit.javascript.host.event.PointerEvent) MouseEvent(com.gargoylesoftware.htmlunit.javascript.host.event.MouseEvent) SgmlPage(com.gargoylesoftware.htmlunit.SgmlPage) MouseEvent(com.gargoylesoftware.htmlunit.javascript.host.event.MouseEvent) Event(com.gargoylesoftware.htmlunit.javascript.host.event.Event) PointerEvent(com.gargoylesoftware.htmlunit.javascript.host.event.PointerEvent) Page(com.gargoylesoftware.htmlunit.Page) SgmlPage(com.gargoylesoftware.htmlunit.SgmlPage)

Example 17 with Event

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

the class HtmlElement method type.

private Page type(final int keyCode, final boolean fireKeyDown, final boolean fireKeyPress, final boolean fireKeyUp, final boolean lastType) {
    if (isDisabledElementAndDisabled()) {
        return getPage();
    }
    final HtmlPage page = (HtmlPage) getPage();
    if (page.getFocusedElement() != this) {
        focus();
    }
    final Event keyDown;
    final ScriptResult keyDownResult;
    if (fireKeyDown) {
        keyDown = new KeyboardEvent(this, Event.TYPE_KEY_DOWN, keyCode, shiftPressed_, ctrlPressed_, altPressed_);
        keyDownResult = fireEvent(keyDown);
    } else {
        keyDown = null;
        keyDownResult = null;
    }
    final BrowserVersion browserVersion = page.getWebClient().getBrowserVersion();
    final Event keyPress;
    final ScriptResult keyPressResult;
    if (fireKeyPress && browserVersion.hasFeature(KEYBOARD_EVENT_SPECIAL_KEYPRESS)) {
        keyPress = new KeyboardEvent(this, Event.TYPE_KEY_PRESS, keyCode, shiftPressed_, ctrlPressed_, altPressed_);
        keyPressResult = fireEvent(keyPress);
    } else {
        keyPress = null;
        keyPressResult = null;
    }
    if (keyDown != null && !keyDown.isAborted(keyDownResult) && (keyPress == null || !keyPress.isAborted(keyPressResult))) {
        doType(keyCode, lastType);
    }
    if (this instanceof HtmlTextInput || this instanceof HtmlTextArea || this instanceof HtmlTelInput || this instanceof HtmlNumberInput || this instanceof HtmlSearchInput || this instanceof HtmlPasswordInput) {
        final Event input = new KeyboardEvent(this, Event.TYPE_INPUT, keyCode, shiftPressed_, ctrlPressed_, altPressed_);
        fireEvent(input);
    }
    if (fireKeyUp) {
        final Event keyUp = new KeyboardEvent(this, Event.TYPE_KEY_UP, keyCode, shiftPressed_, ctrlPressed_, altPressed_);
        fireEvent(keyUp);
    }
    // }
    return page.getWebClient().getCurrentWindow().getEnclosedPage();
}
Also used : ScriptResult(com.gargoylesoftware.htmlunit.ScriptResult) KeyboardEvent(com.gargoylesoftware.htmlunit.javascript.host.event.KeyboardEvent) Event(com.gargoylesoftware.htmlunit.javascript.host.event.Event) KeyboardEvent(com.gargoylesoftware.htmlunit.javascript.host.event.KeyboardEvent) BrowserVersion(com.gargoylesoftware.htmlunit.BrowserVersion)

Example 18 with Event

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

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

the class HtmlImage method doOnLoad.

/**
 * <p><span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span></p>
 *
 * <p>Executes this element's <tt>onload</tt> or <tt>onerror</tt> handler. This method downloads the image
 * if either of these handlers are present (prior to invoking the resulting handler), because applications
 * sometimes use images to send information to the server and use these handlers to get notified when the
 * information has been received by the server.</p>
 *
 * <p>See <a href="http://www.nabble.com/How-should-we-handle-image.onload--tt9850876.html">here</a> and
 * <a href="http://www.nabble.com/Image-Onload-Support-td18895781.html">here</a> for the discussion which
 * lead up to this method.</p>
 *
 * <p>This method may be called multiple times, but will only attempt to execute the <tt>onload</tt> or
 * <tt>onerror</tt> handler the first time it is invoked.</p>
 */
public void doOnLoad() {
    if (onloadProcessed_) {
        return;
    }
    final HtmlPage htmlPage = getHtmlPageOrNull();
    if (htmlPage == null) {
        // nothing to do if embedded in XML code
        return;
    }
    final WebClient client = htmlPage.getWebClient();
    final boolean hasEventHandler = hasEventHandlers("onload") || hasEventHandlers("onerror");
    if (((hasEventHandler && client.isJavaScriptEnabled()) || client.getOptions().isDownloadImages()) && hasAttribute(SRC_ATTRIBUTE)) {
        boolean loadSuccessful = false;
        final boolean tryDownload;
        if (hasFeature(HTMLIMAGE_BLANK_SRC_AS_EMPTY)) {
            tryDownload = !StringUtils.isBlank(getSrcAttribute());
        } else {
            tryDownload = !getSrcAttribute().isEmpty();
        }
        if (tryDownload) {
            // We need to download the image and then call the resulting handler.
            try {
                downloadImageIfNeeded();
                // if the download was a success
                if (imageWebResponse_.isSuccess()) {
                    // Trigger the onload handler
                    loadSuccessful = true;
                }
            } catch (final IOException e) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("IOException while downloading image for '" + this + "' : " + e.getMessage());
                }
            }
        }
        if (!client.isJavaScriptEnabled()) {
            onloadProcessed_ = true;
            return;
        }
        if (!hasEventHandler) {
            return;
        }
        onloadProcessed_ = true;
        final Event event = new Event(this, loadSuccessful ? Event.TYPE_LOAD : Event.TYPE_ERROR);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Firing the " + event.getType() + " event for '" + this + "'.");
        }
        if (READY_STATE_LOADING.equals(htmlPage.getReadyState())) {
            final PostponedAction action = new PostponedAction(getPage(), "HtmlImage.doOnLoad") {

                @Override
                public void execute() throws Exception {
                    HtmlImage.this.fireEvent(event);
                }
            };
            htmlPage.addAfterLoadAction(action);
        } else {
            fireEvent(event);
        }
    }
}
Also used : MouseEvent(com.gargoylesoftware.htmlunit.javascript.host.event.MouseEvent) Event(com.gargoylesoftware.htmlunit.javascript.host.event.Event) PostponedAction(com.gargoylesoftware.htmlunit.javascript.PostponedAction) IOException(java.io.IOException) WebClient(com.gargoylesoftware.htmlunit.WebClient)

Example 20 with Event

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

the class FileReader method readAsDataURL.

/**
 * Reads the contents of the specified {@link Blob} or {@link File}.
 * @param object the {@link Blob} or {@link File} from which to read
 * @throws IOException if an error occurs
 */
@JsxFunction
public void readAsDataURL(final Object object) throws IOException {
    readyState_ = LOADING;
    result_ = DataURLConnection.DATA_PREFIX;
    final byte[] bytes = ((Blob) object).getBytes();
    final String value = new String(new Base64().encode(bytes), StandardCharsets.US_ASCII);
    final BrowserVersion browserVersion = getBrowserVersion();
    String contentType = ((Blob) object).getType();
    if (StringUtils.isEmpty(contentType) && !browserVersion.hasFeature(JS_FILEREADER_EMPTY_NULL)) {
        contentType = MimeType.APPLICATION_OCTET_STREAM;
    }
    if (object instanceof File) {
        final java.io.File file = ((File) object).getFile();
        if (value.isEmpty()) {
            contentType = URLConnection.guessContentTypeFromName(file.getName());
        } else {
            contentType = Files.probeContentType(file.toPath());
        // this is a bit weak, on linux we get different results
        // e.g. 'application/octet-stream' for a file with random bits
        // instead of null on windows
        }
    }
    if (browserVersion.hasFeature(JS_FILEREADER_EMPTY_NULL)) {
        if (value.isEmpty()) {
            result_ = "null";
        } else {
            if (contentType != null) {
                result_ += contentType;
            }
            result_ += ";base64," + value;
        }
    } else {
        final boolean includeConentType = browserVersion.hasFeature(JS_FILEREADER_CONTENT_TYPE);
        if (!value.isEmpty() || includeConentType) {
            if (contentType == null) {
                contentType = MimeType.APPLICATION_OCTET_STREAM;
            }
            result_ += contentType + ";base64," + value;
        }
    }
    readyState_ = DONE;
    final Event event = new Event(this, Event.TYPE_LOAD);
    fireEvent(event);
}
Also used : Base64(org.apache.commons.codec.binary.Base64) Event(com.gargoylesoftware.htmlunit.javascript.host.event.Event) BrowserVersion(com.gargoylesoftware.htmlunit.BrowserVersion) JsxFunction(com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)

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