Search in sources :

Example 1 with Node

use of com.gargoylesoftware.htmlunit.javascript.host.dom.Node in project htmlunit by HtmlUnit.

the class HTMLElement method removeNode.

/**
 * Removes this object from the document hierarchy.
 * @param removeChildren whether to remove children or no
 * @return a reference to the object that is removed
 */
@JsxFunction(IE)
public HTMLElement removeNode(final boolean removeChildren) {
    final HTMLElement parent = (HTMLElement) getParentElement();
    if (parent != null) {
        parent.removeChild(this);
        if (!removeChildren) {
            final NodeList collection = getChildNodes();
            final int length = collection.getLength();
            for (int i = 0; i < length; i++) {
                final Node object = (Node) collection.item(Integer.valueOf(0));
                parent.appendChild(object);
            }
        }
    }
    return this;
}
Also used : NodeList(com.gargoylesoftware.htmlunit.javascript.host.dom.NodeList) DomNode(com.gargoylesoftware.htmlunit.html.DomNode) Node(com.gargoylesoftware.htmlunit.javascript.host.dom.Node) JsxFunction(com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)

Example 2 with Node

use of com.gargoylesoftware.htmlunit.javascript.host.dom.Node in project htmlunit by HtmlUnit.

the class XSLTProcessor method transformToDocument.

/**
 * Transforms the node source applying the stylesheet given by the importStylesheet() function.
 * The owner document of the output node owns the returned document fragment.
 *
 * @param source the node to be transformed
 * @return the result of the transformation
 */
@JsxFunction
public XMLDocument transformToDocument(final Node source) {
    final XMLDocument doc = new XMLDocument();
    doc.setPrototype(getPrototype(doc.getClass()));
    doc.setParentScope(getParentScope());
    final Object transformResult = transform(source);
    final org.w3c.dom.Node node;
    if (transformResult instanceof org.w3c.dom.Node) {
        final org.w3c.dom.Node transformedDoc = (org.w3c.dom.Node) transformResult;
        node = transformedDoc.getFirstChild();
    } else {
        node = null;
    }
    final XmlPage page = new XmlPage(node, getWindow().getWebWindow());
    doc.setDomNode(page);
    return doc;
}
Also used : Node(com.gargoylesoftware.htmlunit.javascript.host.dom.Node) DomNode(com.gargoylesoftware.htmlunit.html.DomNode) XmlPage(com.gargoylesoftware.htmlunit.xml.XmlPage) JsxFunction(com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)

Example 3 with Node

use of com.gargoylesoftware.htmlunit.javascript.host.dom.Node 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 4 with Node

use of com.gargoylesoftware.htmlunit.javascript.host.dom.Node in project htmlunit by HtmlUnit.

the class Element method insertAdjacentElement.

/**
 * Inserts the given element into the element at the location.
 * @param where specifies where to insert the element, using one of the following values (case-insensitive):
 *        beforebegin, afterbegin, beforeend, afterend
 * @param insertedElement the element to be inserted
 * @return an element object
 *
 * @see <a href="http://msdn.microsoft.com/en-us/library/ie/ms536451.aspx">MSDN</a>
 */
@JsxFunction({ CHROME, EDGE, FF, FF_ESR })
public Object insertAdjacentElement(final String where, final Object insertedElement) {
    if (insertedElement instanceof Node) {
        final DomNode childNode = ((Node) insertedElement).getDomNodeOrDie();
        final Object[] values = getInsertAdjacentLocation(where);
        final DomNode node = (DomNode) values[0];
        final boolean append = ((Boolean) values[1]).booleanValue();
        if (append) {
            node.appendChild(childNode);
        } else {
            node.insertBefore(childNode);
        }
        return insertedElement;
    }
    throw Context.reportRuntimeError("Passed object is not an element: " + insertedElement);
}
Also used : ProxyDomNode(com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement.ProxyDomNode) DomNode(com.gargoylesoftware.htmlunit.html.DomNode) ProxyDomNode(com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement.ProxyDomNode) DomNode(com.gargoylesoftware.htmlunit.html.DomNode) Node(com.gargoylesoftware.htmlunit.javascript.host.dom.Node) FunctionObject(net.sourceforge.htmlunit.corejs.javascript.FunctionObject) JsxFunction(com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)

Example 5 with Node

use of com.gargoylesoftware.htmlunit.javascript.host.dom.Node in project htmlunit by HtmlUnit.

the class XMLSerializer method serializeToString.

/**
 * The subtree rooted by the specified element is serialized to a string.
 * @param root the root of the subtree to be serialized (this may be any node, even a document)
 * @return the serialized string
 */
@JsxFunction
public String serializeToString(Node root) {
    if (root == null) {
        return "";
    }
    if (root instanceof DocumentFragment) {
        if (root.getOwnerDocument() instanceof HTMLDocument && getBrowserVersion().hasFeature(JS_XML_SERIALIZER_HTML_DOCUMENT_FRAGMENT_ALWAYS_EMPTY)) {
            return "";
        }
        Node node = root.getFirstChild();
        if (node == null) {
            return "";
        }
        final StringBuilder builder = new StringBuilder();
        while (node != null) {
            builder.append(serializeToString(node));
            node = node.getNextSibling();
        }
        return builder.toString();
    }
    if (root instanceof Document) {
        root = ((Document) root).getDocumentElement();
    }
    if (root instanceof Element) {
        final StringBuilder builder = new StringBuilder();
        final DomNode node = root.getDomNodeOrDie();
        final SgmlPage page = node.getPage();
        final boolean isHtmlPage = page != null && page.isHtmlPage();
        String forcedNamespace = null;
        if (isHtmlPage) {
            forcedNamespace = "http://www.w3.org/1999/xhtml";
        }
        toXml(1, node, builder, forcedNamespace);
        return builder.toString();
    }
    if (root instanceof CDATASection && getBrowserVersion().hasFeature(JS_XML_SERIALIZER_ROOT_CDATA_AS_ESCAPED_TEXT)) {
        final DomCDataSection domCData = (DomCDataSection) root.getDomNodeOrDie();
        final String data = domCData.getData();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(data)) {
            return StringUtils.escapeXmlChars(data);
        }
    }
    return root.getDomNodeOrDie().asXml();
}
Also used : CDATASection(com.gargoylesoftware.htmlunit.javascript.host.dom.CDATASection) HTMLDocument(com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument) Node(com.gargoylesoftware.htmlunit.javascript.host.dom.Node) Element(com.gargoylesoftware.htmlunit.javascript.host.Element) SgmlPage(com.gargoylesoftware.htmlunit.SgmlPage) HTMLDocument(com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument) Document(com.gargoylesoftware.htmlunit.javascript.host.dom.Document) DocumentFragment(com.gargoylesoftware.htmlunit.javascript.host.dom.DocumentFragment) JsxFunction(com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)

Aggregations

Node (com.gargoylesoftware.htmlunit.javascript.host.dom.Node)6 DomNode (com.gargoylesoftware.htmlunit.html.DomNode)5 JsxFunction (com.gargoylesoftware.htmlunit.javascript.configuration.JsxFunction)4 SgmlPage (com.gargoylesoftware.htmlunit.SgmlPage)2 BaseFrameElement (com.gargoylesoftware.htmlunit.html.BaseFrameElement)1 DomText (com.gargoylesoftware.htmlunit.html.DomText)1 FrameWindow (com.gargoylesoftware.htmlunit.html.FrameWindow)1 PageDenied (com.gargoylesoftware.htmlunit.html.FrameWindow.PageDenied)1 HtmlPage (com.gargoylesoftware.htmlunit.html.HtmlPage)1 XHtmlPage (com.gargoylesoftware.htmlunit.html.XHtmlPage)1 Element (com.gargoylesoftware.htmlunit.javascript.host.Element)1 CDATASection (com.gargoylesoftware.htmlunit.javascript.host.dom.CDATASection)1 Document (com.gargoylesoftware.htmlunit.javascript.host.dom.Document)1 DocumentFragment (com.gargoylesoftware.htmlunit.javascript.host.dom.DocumentFragment)1 NodeList (com.gargoylesoftware.htmlunit.javascript.host.dom.NodeList)1 Event (com.gargoylesoftware.htmlunit.javascript.host.event.Event)1 HTMLDocument (com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument)1 ProxyDomNode (com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement.ProxyDomNode)1 XmlPage (com.gargoylesoftware.htmlunit.xml.XmlPage)1 Policy (com.shapesecurity.salvation2.Policy)1