Search in sources :

Example 1 with HTMLDocument

use of com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument in project htmlunit by HtmlUnit.

the class HtmlPage method setFocusedElement.

/**
 * Moves the focus to the specified element. This will trigger any relevant JavaScript
 * event handlers.
 *
 * @param newElement the element that will receive the focus, use {@code null} to remove focus from any element
 * @param windowActivated - whether the enclosing window got focus resulting in specified element getting focus
 * @return true if the specified element now has the focus
 * @see #getFocusedElement()
 */
public boolean setFocusedElement(final DomElement newElement, final boolean windowActivated) {
    if (elementWithFocus_ == newElement && !windowActivated) {
        // nothing to do
        return true;
    }
    final DomElement oldFocusedElement = elementWithFocus_;
    elementWithFocus_ = null;
    if (getWebClient().isJavaScriptEnabled()) {
        final Object o = getScriptableObject();
        if (o instanceof HTMLDocument) {
            ((HTMLDocument) o).setActiveElement(null);
        }
    }
    if (!windowActivated) {
        if (hasFeature(EVENT_FOCUS_IN_FOCUS_OUT_BLUR)) {
            if (oldFocusedElement != null) {
                oldFocusedElement.fireEvent(Event.TYPE_FOCUS_OUT);
            }
            if (newElement != null) {
                newElement.fireEvent(Event.TYPE_FOCUS_IN);
            }
        }
        if (oldFocusedElement != null) {
            oldFocusedElement.removeFocus();
            oldFocusedElement.fireEvent(Event.TYPE_BLUR);
            if (hasFeature(EVENT_FOCUS_FOCUS_IN_BLUR_OUT)) {
                oldFocusedElement.fireEvent(Event.TYPE_FOCUS_OUT);
            }
        }
    }
    elementWithFocus_ = newElement;
    // might be changed by another thread
    if (newElement instanceof SelectableTextInput && hasFeature(PAGE_SELECTION_RANGE_FROM_SELECTABLE_TEXT_INPUT)) {
        final SelectableTextInput sti = (SelectableTextInput) newElement;
        setSelectionRange(new SimpleRange(sti, sti.getSelectionStart(), sti, sti.getSelectionEnd()));
    }
    if (newElement != null) {
        if (getWebClient().isJavaScriptEnabled()) {
            final Object o = getScriptableObject();
            if (o instanceof HTMLDocument) {
                final Object e = newElement.getScriptableObject();
                if (e instanceof HTMLElement) {
                    ((HTMLDocument) o).setActiveElement((HTMLElement) e);
                }
            }
        }
        newElement.focus();
        newElement.fireEvent(Event.TYPE_FOCUS);
        if (hasFeature(EVENT_FOCUS_FOCUS_IN_BLUR_OUT)) {
            newElement.fireEvent(Event.TYPE_FOCUS_IN);
        }
    }
    // element will not have the focus because its page has gone away.
    return this == getEnclosingWindow().getEnclosedPage();
}
Also used : HTMLElement(com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement) HTMLDocument(com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument) ScriptableObject(net.sourceforge.htmlunit.corejs.javascript.ScriptableObject) SimpleRange(com.gargoylesoftware.htmlunit.html.impl.SimpleRange) SelectableTextInput(com.gargoylesoftware.htmlunit.html.impl.SelectableTextInput)

Example 2 with HTMLDocument

use of com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument in project htmlunit by HtmlUnit.

the class EventListenersContainer method executeEventListeners.

private void executeEventListeners(final int eventPhase, final Event event, final Object[] args) {
    final DomNode node = jsNode_.getDomNodeOrNull();
    // some event don't apply on all kind of nodes, for instance "blur"
    if (node != null && !node.handles(event)) {
        return;
    }
    final TypeContainer container = getTypeContainer(event.getType());
    final List<Scriptable> listeners = container.getListeners(eventPhase);
    if (!listeners.isEmpty()) {
        event.setCurrentTarget(jsNode_);
        final HtmlPage page;
        if (jsNode_ instanceof Window) {
            page = (HtmlPage) jsNode_.getDomNodeOrDie();
        } else {
            final Scriptable parentScope = jsNode_.getParentScope();
            if (parentScope instanceof Window) {
                page = (HtmlPage) ((Window) parentScope).getDomNodeOrDie();
            } else if (parentScope instanceof HTMLDocument) {
                page = ((HTMLDocument) parentScope).getPage();
            } else {
                page = ((HTMLElement) parentScope).getDomNodeOrDie().getHtmlPageOrNull();
            }
        }
        // no need for a copy, listeners are copy on write
        for (Scriptable listener : listeners) {
            boolean isPropertyHandler = false;
            if (listener == TypeContainer.EVENT_HANDLER_PLACEHOLDER) {
                listener = container.handler_;
                isPropertyHandler = true;
            }
            Function function = null;
            Scriptable thisObject = null;
            if (listener instanceof Function) {
                function = (Function) listener;
                thisObject = jsNode_;
            } else if (listener instanceof NativeObject) {
                final Object handleEvent = ScriptableObject.getProperty(listener, "handleEvent");
                if (handleEvent instanceof Function) {
                    function = (Function) handleEvent;
                    thisObject = listener;
                }
            }
            if (function != null) {
                final ScriptResult result = page.executeJavaScriptFunction(function, thisObject, args, node);
                // Return value is only honored for property handlers (Tested in Chrome/FF/IE11)
                if (isPropertyHandler && !ScriptResult.isUndefined(result)) {
                    event.handlePropertyHandlerReturnValue(result.getJavaScriptResult());
                }
            }
            if (event.isImmediatePropagationStopped()) {
                return;
            }
        }
    }
}
Also used : Window(com.gargoylesoftware.htmlunit.javascript.host.Window) NativeObject(net.sourceforge.htmlunit.corejs.javascript.NativeObject) ScriptResult(com.gargoylesoftware.htmlunit.ScriptResult) Function(net.sourceforge.htmlunit.corejs.javascript.Function) DomNode(com.gargoylesoftware.htmlunit.html.DomNode) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) HTMLDocument(com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument) NativeObject(net.sourceforge.htmlunit.corejs.javascript.NativeObject) ScriptableObject(net.sourceforge.htmlunit.corejs.javascript.ScriptableObject) Scriptable(net.sourceforge.htmlunit.corejs.javascript.Scriptable)

Example 3 with HTMLDocument

use of com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument in project htmlunit by HtmlUnit.

the class DomNode method getSelectorList.

/**
 * Returns the {@link SelectorList}.
 * @param selectors the selectors
 * @param browserVersion the {@link BrowserVersion}
 * @return the {@link SelectorList}
 * @throws IOException if an error occurs
 */
protected SelectorList getSelectorList(final String selectors, final BrowserVersion browserVersion) throws IOException {
    final CSSOMParser parser = new CSSOMParser(new CSS3Parser());
    final CheckErrorHandler errorHandler = new CheckErrorHandler();
    parser.setErrorHandler(errorHandler);
    final SelectorList selectorList = parser.parseSelectors(selectors);
    // in case of error parseSelectors returns null
    if (errorHandler.errorDetected()) {
        throw new CSSException("Invalid selectors: " + selectors);
    }
    if (selectorList != null) {
        int documentMode = 9;
        if (browserVersion.hasFeature(QUERYSELECTORALL_NOT_IN_QUIRKS)) {
            final Object sobj = getPage().getScriptableObject();
            if (sobj instanceof HTMLDocument) {
                documentMode = ((HTMLDocument) sobj).getDocumentMode();
            }
        }
        CSSStyleSheet.validateSelectors(selectorList, documentMode, this);
    }
    return selectorList;
}
Also used : HTMLDocument(com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument) CSSOMParser(com.gargoylesoftware.css.parser.CSSOMParser) CSS3Parser(com.gargoylesoftware.css.parser.javacc.CSS3Parser) SelectorList(com.gargoylesoftware.css.parser.selector.SelectorList) CSSException(com.gargoylesoftware.css.parser.CSSException) ScriptableObject(net.sourceforge.htmlunit.corejs.javascript.ScriptableObject)

Example 4 with HTMLDocument

use of com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument in project htmlunit by HtmlUnit.

the class HTMLCollectionFrames method initialize.

/**
 * Initializes this window.
 * @param webWindow the web window corresponding to this window
 * @param pageToEnclose the page that will become the enclosing page
 */
public void initialize(final WebWindow webWindow, final Page pageToEnclose) {
    webWindow_ = webWindow;
    webWindow_.setScriptableObject(this);
    windowProxy_ = new WindowProxy(webWindow_);
    if (pageToEnclose instanceof XmlPage) {
        document_ = new XMLDocument();
    } else {
        document_ = new HTMLDocument();
    }
    document_.setParentScope(this);
    document_.setPrototype(getPrototype(document_.getClass()));
    document_.setWindow(this);
    if (pageToEnclose instanceof SgmlPage) {
        final SgmlPage page = (SgmlPage) pageToEnclose;
        document_.setDomNode(page);
        if (page.isHtmlPage()) {
            final HtmlPage htmlPage = (HtmlPage) page;
            htmlPage.addAutoCloseable(this);
        }
    }
    documentProxy_ = new DocumentProxy(webWindow_);
    navigator_ = new Navigator();
    navigator_.setParentScope(this);
    navigator_.setPrototype(getPrototype(navigator_.getClass()));
    screen_ = new Screen(getWebWindow().getScreen());
    screen_.setParentScope(this);
    screen_.setPrototype(getPrototype(screen_.getClass()));
    history_ = new History();
    history_.setParentScope(this);
    history_.setPrototype(getPrototype(history_.getClass()));
    location_ = new Location();
    location_.setParentScope(this);
    location_.setPrototype(getPrototype(location_.getClass()));
    location_.initialize(this, pageToEnclose);
    final Console console = new Console();
    console.setWebWindow(webWindow_);
    console.setParentScope(this);
    console.setPrototype(getPrototype(console.getClass()));
    console_ = console;
    applicationCache_ = new ApplicationCache();
    applicationCache_.setParentScope(this);
    applicationCache_.setPrototype(getPrototype(applicationCache_.getClass()));
    // like a JS new Object()
    final Context ctx = Context.getCurrentContext();
    controllers_ = ctx.newObject(this);
    if (webWindow_ instanceof TopLevelWindow) {
        final WebWindow opener = ((TopLevelWindow) webWindow_).getOpener();
        if (opener != null) {
            opener_ = opener.getScriptableObject();
        }
    }
}
Also used : Context(net.sourceforge.htmlunit.corejs.javascript.Context) HtmlPage(com.gargoylesoftware.htmlunit.html.HtmlPage) HTMLDocument(com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument) XMLDocument(com.gargoylesoftware.htmlunit.javascript.host.xml.XMLDocument) WebWindow(com.gargoylesoftware.htmlunit.WebWindow) SgmlPage(com.gargoylesoftware.htmlunit.SgmlPage) XmlPage(com.gargoylesoftware.htmlunit.xml.XmlPage) DocumentProxy(com.gargoylesoftware.htmlunit.javascript.host.html.DocumentProxy) TopLevelWindow(com.gargoylesoftware.htmlunit.TopLevelWindow)

Example 5 with HTMLDocument

use of com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument in project htmlunit by HtmlUnit.

the class XMLHttpRequest method prepareRequestContent.

/**
 * Prepares the WebRequest that will be sent.
 * @param content the content to send
 */
private void prepareRequestContent(final Object content) {
    if (content != null && (HttpMethod.POST == webRequest_.getHttpMethod() || HttpMethod.PUT == webRequest_.getHttpMethod() || HttpMethod.PATCH == webRequest_.getHttpMethod()) && !Undefined.isUndefined(content)) {
        final boolean setEncodingType = webRequest_.getAdditionalHeader(HttpHeader.CONTENT_TYPE) == null;
        if (content instanceof HTMLDocument) {
            // final String body = ((HTMLDocument) content).getDomNodeOrDie().asXml();
            final String body = new XMLSerializer().serializeToString((HTMLDocument) content);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Setting request body to: " + body);
            }
            webRequest_.setRequestBody(body);
            if (setEncodingType) {
                webRequest_.setAdditionalHeader(HttpHeader.CONTENT_TYPE, "text/html;charset=UTF-8");
            }
        } else if (content instanceof XMLDocument) {
            // this output differs from real browsers but it seems to be a good starting point
            try (StringWriter writer = new StringWriter()) {
                final XMLDocument xmlDocument = (XMLDocument) content;
                final Transformer transformer = TransformerFactory.newInstance().newTransformer();
                transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                transformer.setOutputProperty(OutputKeys.INDENT, "no");
                transformer.transform(new DOMSource(xmlDocument.getDomNodeOrDie().getFirstChild()), new StreamResult(writer));
                final String body = writer.toString();
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Setting request body to: " + body);
                }
                webRequest_.setRequestBody(body);
                if (setEncodingType) {
                    webRequest_.setAdditionalHeader(HttpHeader.CONTENT_TYPE, MimeType.APPLICATION_XML + ";charset=UTF-8");
                }
            } catch (final Exception e) {
                Context.throwAsScriptRuntimeEx(e);
            }
        } else if (content instanceof FormData) {
            ((FormData) content).fillRequest(webRequest_);
        } else if (content instanceof NativeArrayBufferView) {
            final NativeArrayBufferView view = (NativeArrayBufferView) content;
            webRequest_.setRequestBody(new String(view.getBuffer().getBuffer(), UTF_8));
            if (setEncodingType) {
                webRequest_.setEncodingType(null);
            }
        } else if (content instanceof URLSearchParams) {
            ((URLSearchParams) content).fillRequest(webRequest_);
            webRequest_.addHint(HttpHint.IncludeCharsetInContentTypeHeader);
        } else if (content instanceof Blob) {
            ((Blob) content).fillRequest(webRequest_);
        } else {
            final String body = Context.toString(content);
            if (!body.isEmpty()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Setting request body to: " + body);
                }
                webRequest_.setRequestBody(body);
                webRequest_.setCharset(UTF_8);
                if (setEncodingType) {
                    webRequest_.setEncodingType(FormEncodingType.TEXT_PLAIN);
                }
            }
        }
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Blob(com.gargoylesoftware.htmlunit.javascript.host.file.Blob) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) HTMLDocument(com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument) URLSearchParams(com.gargoylesoftware.htmlunit.javascript.host.URLSearchParams) NoHttpResponseException(org.apache.http.NoHttpResponseException) SocketTimeoutException(java.net.SocketTimeoutException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) ParseException(net.sourceforge.htmlunit.corejs.javascript.json.JsonParser.ParseException) StringWriter(java.io.StringWriter) NativeArrayBufferView(net.sourceforge.htmlunit.corejs.javascript.typedarrays.NativeArrayBufferView)

Aggregations

HTMLDocument (com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument)13 HtmlPage (com.gargoylesoftware.htmlunit.html.HtmlPage)7 WebWindow (com.gargoylesoftware.htmlunit.WebWindow)4 Window (com.gargoylesoftware.htmlunit.javascript.host.Window)4 SgmlPage (com.gargoylesoftware.htmlunit.SgmlPage)3 DomElement (com.gargoylesoftware.htmlunit.html.DomElement)3 IOException (java.io.IOException)3 ScriptableObject (net.sourceforge.htmlunit.corejs.javascript.ScriptableObject)3 CSSException (com.gargoylesoftware.css.parser.CSSException)2 CSSOMParser (com.gargoylesoftware.css.parser.CSSOMParser)2 CSS3Parser (com.gargoylesoftware.css.parser.javacc.CSS3Parser)2 SelectorList (com.gargoylesoftware.css.parser.selector.SelectorList)2 StringWebResponse (com.gargoylesoftware.htmlunit.StringWebResponse)2 WebResponse (com.gargoylesoftware.htmlunit.WebResponse)2 DomNode (com.gargoylesoftware.htmlunit.html.DomNode)2 HTMLParser (com.gargoylesoftware.htmlunit.html.parser.HTMLParser)2 JsxFunction (com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)2 Element (com.gargoylesoftware.htmlunit.javascript.host.Element)2 HTMLElement (com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement)2 CSSErrorHandler (com.gargoylesoftware.css.parser.CSSErrorHandler)1