com.gargoylesoftware.htmlunit.WebWindow Java Examples

The following examples show how to use com.gargoylesoftware.htmlunit.WebWindow. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Document.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the domain name of the server that served the document, or {@code null} if the server
 * cannot be identified by a domain name.
 * @return the domain name of the server that served the document
 * @see <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one-html.html#ID-2250147">
 * W3C documentation</a>
 */
@JsxGetter({CHROME, IE})
public String getDomain() {
    if (domain_ == null && getPage().getWebResponse() != null) {
        URL url = getPage().getUrl();
        if (url == WebClient.URL_ABOUT_BLANK) {
            final WebWindow w = getWindow().getWebWindow();
            if (w instanceof FrameWindow) {
                url = ((FrameWindow) w).getEnclosingPage().getUrl();
            }
            else {
                return null;
            }
        }
        domain_ = url.getHost().toLowerCase(Locale.ROOT);
    }

    return domain_;
}
 
Example #2
Source File: Window.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a modal dialog box that displays the specified HTML document.
 * @param url the URL of the document to load and display
 * @param arguments object to be made available via <tt>window.dialogArguments</tt> in the dialog window
 * @param features string that specifies the window ornaments for the dialog window
 * @return the value of the {@code returnValue} property as set by the modal dialog's window
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms536759.aspx">MSDN Documentation</a>
 * @see <a href="https://developer.mozilla.org/en/DOM/window.showModalDialog">Mozilla Documentation</a>
 */
@JsxFunction({IE, FF})
public Object showModalDialog(final String url, final Object arguments, final String features) {
    final WebWindow webWindow = getWebWindow();
    final WebClient client = webWindow.getWebClient();
    try {
        final URL completeUrl = ((HtmlPage) getDomNodeOrDie()).getFullyQualifiedUrl(url);
        final DialogWindow dialog = client.openDialogWindow(completeUrl, webWindow, arguments);
        // TODO: Theoretically, we shouldn't return until the dialog window has been close()'ed...
        // But we have to return so that the window can be close()'ed...
        // Maybe we can use Rhino's continuation support to save state and restart when
        // the dialog window is close()'ed? Would only work in interpreted mode, though.
        final ScriptableObject jsDialog = dialog.getScriptableObject();
        return jsDialog.get("returnValue", jsDialog);
    }
    catch (final IOException e) {
        throw Context.throwAsScriptRuntimeEx(e);
    }
}
 
Example #3
Source File: HTMLDocument.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Sets the specified element as the document's active element.
 * @see HTMLElement#setActive()
 * @param element the new active element for this document
 */
public void setActiveElement(final HTMLElement element) {
    // TODO update page focus element also

    activeElement_ = element;

    if (element != null) {
        // if this is part of an iFrame, make the iFrame tag the
        // active element of his doc
        final WebWindow window = element.getDomNodeOrDie().getPage().getEnclosingWindow();
        if (window instanceof FrameWindow) {
            final BaseFrameElement frame = ((FrameWindow) window).getFrameElement();
            if (frame instanceof HtmlInlineFrame) {
                final Window winWithFrame = frame.getPage().getEnclosingWindow().getScriptableObject();
                ((HTMLDocument) winWithFrame.getDocument()).setActiveElement(
                            (HTMLElement) frame.getScriptableObject());
            }
        }
    }
}
 
Example #4
Source File: JavaScriptEngine.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Performs initialization for the given webWindow.
 * @param webWindow the web window to initialize for
 */
@Override
public void initialize(final WebWindow webWindow) {
    WebAssert.notNull("webWindow", webWindow);

    getContextFactory().call(cx -> {
        try {
            init(webWindow, cx);
        }
        catch (final Exception e) {
            LOG.error("Exception while initializing JavaScript for the page", e);
            throw new ScriptException(null, e); // BUG: null is not useful.
        }
        return null;
    });
}
 
Example #5
Source File: AbstractHtmlEngine.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
private boolean isAlreadyLoadedByAncestor(
                                           final URL url,
                                           HtmlPage page ) {

    WebWindow window = page.getEnclosingWindow();
    while (window != null) {
        if (url.sameFile(window.getEnclosedPage().getWebResponse().getWebRequest().getUrl())) {
            return true;
        }
        if (window == window.getParentWindow()) {
            window = null;
        } else {
            window = window.getParentWindow();
        }
    }
    return false;
}
 
Example #6
Source File: HTMLDocument.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private void scheduleImplicitClose() {
    if (!closePostponedAction_) {
        closePostponedAction_ = true;
        final HtmlPage page = (HtmlPage) getDomNodeOrDie();
        final WebWindow enclosingWindow = page.getEnclosingWindow();
        page.getWebClient().getJavaScriptEngine().addPostponedAction(new PostponedAction(page) {
            @Override
            public void execute() throws Exception {
                if (writeBuilder_.length() != 0) {
                    close();
                }
                closePostponedAction_ = false;
            }

            @Override
            public boolean isStillAlive() {
                return !enclosingWindow.isClosed();
            }
        });
    }
}
 
Example #7
Source File: HTMLDocument.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * JavaScript function "open".
 *
 * See http://www.whatwg.org/specs/web-apps/current-work/multipage/section-dynamic.html for
 * a good description of the semantics of open(), write(), writeln() and close().
 *
 * @param url when a new document is opened, <i>url</i> is a String that specifies a MIME type for the document.
 *        When a new window is opened, <i>url</i> is a String that specifies the URL to render in the new window
 * @param name the name
 * @param features the features
 * @param replace whether to replace in the history list or no
 * @return a reference to the new document object.
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms536652.aspx">MSDN documentation</a>
 */
@JsxFunction
public Object open(final Object url, final Object name, final Object features,
        final Object replace) {
    // Any open() invocations are ignored during the parsing stage, because write() and
    // writeln() invocations will directly append content to the current insertion point.
    final HtmlPage page = getPage();
    if (page.isBeingParsed()) {
        LOG.warn("Ignoring call to open() during the parsing stage.");
        return null;
    }

    // We're not in the parsing stage; OK to continue.
    if (!writeInCurrentDocument_) {
        LOG.warn("Function open() called when document is already open.");
    }
    writeInCurrentDocument_ = false;
    final WebWindow ww = getWindow().getWebWindow();
    if (ww instanceof FrameWindow
            && WebClient.ABOUT_BLANK.equals(getPage().getUrl().toExternalForm())) {
        final URL enclosingUrl = ((FrameWindow) ww).getEnclosingPage().getUrl();
        getPage().getWebResponse().getWebRequest().setUrl(enclosingUrl);
    }
    return this;
}
 
Example #8
Source File: Document.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the domain name of the server that served the document, or {@code null} if the server
 * cannot be identified by a domain name.
 * @return the domain name of the server that served the document
 * @see <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one-html.html#ID-2250147">
 * W3C documentation</a>
 */
@JsxGetter({CHROME, IE})
public String getDomain() {
    if (domain_ == null && getPage().getWebResponse() != null) {
        URL url = getPage().getUrl();
        if (url == WebClient.URL_ABOUT_BLANK) {
            final WebWindow w = getWindow().getWebWindow();
            if (w instanceof FrameWindow) {
                url = ((FrameWindow) w).getEnclosingPage().getUrl();
            }
            else {
                return null;
            }
        }
        domain_ = url.getHost().toLowerCase(Locale.ROOT);
    }

    return domain_;
}
 
Example #9
Source File: HtmlFrameSetTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void loadingIFrames() throws Exception {
    final String firstContent
        = "<html><head><title>First</title></head>\n"
        + "<body>\n"
        + "  <iframe name='left' src='" + URL_SECOND + "' />\n"
        + "  some stuff"
        + "</html>";
    final String secondContent = "<html><head><title>Second</title></head><body></body></html>";

    final WebClient webClient = getWebClientWithMockWebConnection();

    final MockWebConnection webConnection = getMockWebConnection();
    webConnection.setResponse(URL_FIRST, firstContent);
    webConnection.setResponse(URL_SECOND, secondContent);

    final HtmlPage firstPage = webClient.getPage(URL_FIRST);
    assertEquals("First", firstPage.getTitleText());

    final WebWindow secondWebWindow = webClient.getWebWindowByName("left");
    assertTrue(FrameWindow.class.isInstance(secondWebWindow));
    assertSame(firstPage, ((FrameWindow) secondWebWindow).getEnclosingPage());
    assertEquals("Second", ((HtmlPage) secondWebWindow.getEnclosedPage()).getTitleText());
}
 
Example #10
Source File: XMLDocument.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Loads an XML document from the specified location.
 *
 * @param xmlSource a string containing a URL that specifies the location of the XML file
 * @return true if the load succeeded; false if the load failed
 */
@JsxFunction({FF68, FF60})
public boolean load(final String xmlSource) {
    if (async_) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("XMLDocument.load(): 'async' is true, currently treated as false.");
        }
    }
    try {
        final WebWindow ww = getWindow().getWebWindow();
        final HtmlPage htmlPage = (HtmlPage) ww.getEnclosedPage();
        final WebRequest request = new WebRequest(htmlPage.getFullyQualifiedUrl(xmlSource));
        final WebResponse webResponse = ww.getWebClient().loadWebResponse(request);
        final XmlPage page = new XmlPage(webResponse, ww, false);
        setDomNode(page);
        return true;
    }
    catch (final IOException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Error parsing XML from '" + xmlSource + "'", e);
        }
        return false;
    }
}
 
Example #11
Source File: HtmlFormTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that the result of the form will get loaded into the window specified by "target".
 * @throws Exception if the test fails
 */
@Test
public void submitToTargetWindow() throws Exception {
    final String html
        = "<html><head><title>first</title></head><body>\n"
        + "<form id='form1' target='window2' action='" + URL_SECOND + "' method='post'>\n"
        + "  <input type='submit' name='button' value='push me'/>\n"
        + "</form></body></html>";
    final WebClient client = getWebClientWithMockWebConnection();

    final MockWebConnection webConnection = getMockWebConnection();
    webConnection.setResponse(URL_FIRST, html);
    webConnection.setResponseAsGenericHtml(URL_SECOND, "second");

    final HtmlPage page = client.getPage(URL_FIRST);
    final WebWindow firstWindow = client.getCurrentWindow();
    assertEquals("first window name", "", firstWindow.getName());
    assertSame(page, firstWindow.getEnclosedPage());

    final HtmlForm form = page.getHtmlElementById("form1");

    final HtmlSubmitInput button = form.getInputByName("button");
    final HtmlPage secondPage = button.click();
    assertEquals("window2", secondPage.getEnclosingWindow().getName());
    assertSame(secondPage.getEnclosingWindow(), client.getCurrentWindow());
}
 
Example #12
Source File: DomElementTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts({"2", "2"})
public void getElementsByTagName() throws Exception {
    final String html = "<html><head><script>\n"
            + "function test() {\n"
            + "  alert(document.f1.getElementsByTagName('input').length);\n"
            + "  alert(document.f1.getElementsByTagName('INPUT').length);\n"
            + "}\n"
            + "</script></head>\n"
            + "<body onload='test()'>\n"
            + "  <form name='f1'>\n"
            + "    <input>\n"
            + "    <INPUT>\n"
            + "  </form>\n"
            + "</body></html>";

    final WebDriver driver = loadPageWithAlerts2(html);
    if (driver instanceof HtmlUnitDriver) {
        final WebWindow webWindow = getWebWindowOf((HtmlUnitDriver) driver);
        final HtmlPage page = (HtmlPage) webWindow.getEnclosedPage();
        assertEquals(2, page.getForms().get(0).getElementsByTagName("input").size());
        assertEquals(2, page.getForms().get(0).getElementsByTagName("INPUT").size());
    }
}
 
Example #13
Source File: Location.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Reloads the current page, possibly forcing retrieval from the server even if
 * the browser cache contains the latest version of the document.
 * @param force if {@code true}, force reload from server; otherwise, may reload from cache
 * @throws IOException if there is a problem reloading the page
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms536342.aspx">MSDN Documentation</a>
 */
@JsxFunction
public void reload(final boolean force) throws IOException {
    final HtmlPage htmlPage = (HtmlPage) getWindow(getStartingScope()).getWebWindow().getEnclosedPage();
    final WebRequest request = htmlPage.getWebResponse().getWebRequest();

    String referer = htmlPage.getUrl().toExternalForm();
    request.setAdditionalHeader(HttpHeader.REFERER, referer);

    referer = UrlUtils.getUrlWithNewQuery(htmlPage.getUrl(), null).toExternalForm();
    referer = StringUtils.stripEnd(referer, "/");
    request.setAdditionalHeader(HttpHeader.ORIGIN, referer);

    final WebWindow webWindow = window_.getWebWindow();
    webWindow.getWebClient().download(webWindow, "", request, true, false, "JS location.reload");
}
 
Example #14
Source File: Window.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
@Override
protected Object getWithPreemption(final String name) {
    final List<DomNode> elements = getElements();

    for (final Object next : elements) {
        final BaseFrameElement frameElt = (BaseFrameElement) next;
        final WebWindow window = frameElt.getEnclosedWindow();
        if (name.equals(window.getName())) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Property \"" + name + "\" evaluated (by name) to " + window);
            }
            return getScriptableForElement(window);
        }
        if (getBrowserVersion().hasFeature(JS_WINDOW_FRAMES_ACCESSIBLE_BY_ID) && frameElt.getId().equals(name)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Property \"" + name + "\" evaluated (by id) to " + window);
            }
            return getScriptableForElement(window);
        }
    }

    return NOT_FOUND;
}
 
Example #15
Source File: HudsonPageCreator.java    From jenkins-test-harness with MIT License 5 votes vote down vote up
@Override
public Page createPage(WebResponse webResponse, WebWindow webWindow) throws IOException {
    String contentType = webResponse.getContentType().toLowerCase(Locale.ENGLISH);
    if (contentType.equals("application/x-java-jnlp-file")) {
        return createXmlPage(webResponse, webWindow);
    }
    // Need to sidestep HtmlUnit default behaviour here. It defaults the response type to
    // being text/plain (and so creates a TextPage) if the content type in the response is
    // blank + is an empty response.
    if (contentType.isEmpty()) {
        return createHtmlPage(webResponse, webWindow);
    }

    return super.createPage(webResponse, webWindow);
}
 
Example #16
Source File: HtmlPage.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Deregister frames that are no longer in use.
 */
public void deregisterFramesIfNeeded() {
    for (final WebWindow window : getFrames()) {
        getWebClient().deregisterWebWindow(window);
        final Page page = window.getEnclosedPage();
        if (page != null && page.isHtmlPage()) {
            // seems quite silly, but for instance if the src attribute of an iframe is not
            // set, the error only occurs when leaving the page
            ((HtmlPage) page).deregisterFramesIfNeeded();
        }
    }
}
 
Example #17
Source File: XMLDOMDocument.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Loads an XML document using the supplied string.
 * @param strXML the XML string to load into this XML document object;
 *     this string can contain an entire XML document or a well-formed fragment
 * @return {@code true} if the load succeeded; {@code false} if the load failed
 */
@JsxFunction
public boolean loadXML(final String strXML) {
    try {
        final WebWindow webWindow = getWindow().getWebWindow();

        final WebResponse webResponse = new StringWebResponse(strXML, webWindow.getEnclosedPage().getUrl());
        final XmlPage page = new XmlPage(webResponse, webWindow, false, false);
        setDomNode(page);

        preserveWhiteSpaceDuringLoad_ = preserveWhiteSpace_;
        url_ = "";
        return true;
    }
    catch (final IOException e) {
        final XMLDOMParseError parseError = getParseError();
        parseError.setErrorCode(-1);
        parseError.setFilepos(1);
        parseError.setLine(1);
        parseError.setLinepos(1);
        parseError.setReason(e.getMessage());
        parseError.setSrcText("xml");
        parseError.setUrl("");
        if (LOG.isDebugEnabled()) {
            LOG.debug("Error parsing XML\n" + strXML, e);
        }
        return false;
    }
}
 
Example #18
Source File: HtmlPage.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Deregister frames that are no longer in use.
 */
public void deregisterFramesIfNeeded() {
    for (final WebWindow window : getFrames()) {
        getWebClient().deregisterWebWindow(window);
        final Page page = window.getEnclosedPage();
        if (page != null && page.isHtmlPage()) {
            // seems quite silly, but for instance if the src attribute of an iframe is not
            // set, the error only occurs when leaving the page
            ((HtmlPage) page).deregisterFramesIfNeeded();
        }
    }
}
 
Example #19
Source File: WebClientUtils.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Attaches a visual (GUI) debugger to the specified client.
 * @param client the client to which the visual debugger is to be attached
 * @see <a href="http://www.mozilla.org/rhino/debugger.html">Mozilla Rhino Debugger Documentation</a>
 */
public static void attachVisualDebugger(final WebClient client) {
    final ScopeProvider sp = null;
    final HtmlUnitContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
    final Main main = Main.mainEmbedded(cf, sp, "HtmlUnit JavaScript Debugger");
    main.getDebugFrame().setExtendedState(Frame.MAXIMIZED_BOTH);

    final SourceProvider sourceProvider = new SourceProvider() {
        @Override
        public String getSource(final DebuggableScript script) {
            String sourceName = script.getSourceName();
            if (sourceName.endsWith("(eval)") || sourceName.endsWith("(Function)")) {
                return null; // script is result of eval call. Rhino already knows the source and we don't
            }
            if (sourceName.startsWith("script in ")) {
                sourceName = StringUtils.substringBetween(sourceName, "script in ", " from");
                for (final WebWindow ww : client.getWebWindows()) {
                    final WebResponse wr = ww.getEnclosedPage().getWebResponse();
                    if (sourceName.equals(wr.getWebRequest().getUrl().toString())) {
                        return wr.getContentAsString();
                    }
                }
            }
            return null;
        }
    };
    main.setSourceProvider(sourceProvider);
}
 
Example #20
Source File: MSXMLActiveXObjectFactory.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an instance of the ActiveX object for the given name.
 *
 * @param activeXName the ActiveX name to create an object for
 * @param enclosingWindow the enclosing window
 * @return the created ActiveX object
 */
public Scriptable create(final String activeXName, final WebWindow enclosingWindow) {
    if (isXMLDOMDocument(activeXName)) {
        return createXMLDOMDocument(enclosingWindow);
    }

    if (isXMLHTTPRequest(activeXName)) {
        return createXMLHTTPRequest();
    }

    if (isXSLTemplate(activeXName)) {
        return createXSLTemplate();
    }
    return null;
}
 
Example #21
Source File: Location.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the location URL to an entirely new value.
 * @param newLocation the new location URL
 * @throws IOException if loading the specified location fails
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms533867.aspx">MSDN Documentation</a>
 */
@JsxSetter
public void setHref(final String newLocation) throws IOException {
    final HtmlPage page = (HtmlPage) getWindow(getStartingScope()).getWebWindow().getEnclosedPage();
    if (newLocation.startsWith(JavaScriptURLConnection.JAVASCRIPT_PREFIX)) {
        final String script = newLocation.substring(11);
        page.executeJavaScript(script, "new location value", 1);
        return;
    }
    try {
        URL url = page.getFullyQualifiedUrl(newLocation);
        // fix for empty url
        if (StringUtils.isEmpty(newLocation)) {
            final boolean dropFilename = page.getWebClient().getBrowserVersion().
                    hasFeature(ANCHOR_EMPTY_HREF_NO_FILENAME);
            if (dropFilename) {
                String path = url.getPath();
                path = path.substring(0, path.lastIndexOf('/') + 1);
                url = UrlUtils.getUrlWithNewPath(url, path);
                url = UrlUtils.getUrlWithNewRef(url, null);
            }
            else {
                url = UrlUtils.getUrlWithNewRef(url, null);
            }
        }

        final WebRequest request = new WebRequest(url);
        request.setAdditionalHeader(HttpHeader.REFERER, page.getUrl().toExternalForm());

        final WebWindow webWindow = window_.getWebWindow();
        webWindow.getWebClient().download(webWindow, "", request, true, false, "JS set location");
    }
    catch (final MalformedURLException e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("setHref('" + newLocation + "') got MalformedURLException", e);
        }
        throw e;
    }
}
 
Example #22
Source File: Window.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
@Override
protected Scriptable getScriptableForElement(final Object obj) {
    final WebWindow window;
    if (obj instanceof BaseFrameElement) {
        window = ((BaseFrameElement) obj).getEnclosedWindow();
    }
    else {
        window = ((FrameWindow) obj).getFrameElement().getEnclosedWindow();
    }

    return window.getScriptableObject();
}
 
Example #23
Source File: XMLDocument.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
private static XmlPage createParserErrorXmlPage(final String message, final WebWindow webWindow)
        throws IOException {
    final String xml = "<parsererror xmlns=\"http://www.mozilla.org/newlayout/xml/parsererror.xml\">\n"
        + message + "\n"
        + "<sourcetext></sourcetext>\n"
        + "</parsererror>";

    final WebResponse webResponse = new StringWebResponse(xml, webWindow.getEnclosedPage().getUrl());

    return new XmlPage(webResponse, webWindow, false);
}
 
Example #24
Source File: MSXMLActiveXObjectFactory.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private XMLDOMDocument createXMLDOMDocument(final WebWindow enclosingWindow) {
    final XMLDOMDocument document = new XMLDOMDocument(enclosingWindow);
    initObject(document);

    try {
        document.setParentScope(enclosingWindow.getScriptableObject());
    }
    catch (final Exception e) {
        LOG.error("Exception while initializing JavaScript for the page", e);
        throw new ScriptException(null, e); // BUG: null is not useful.
    }
    return document;
}
 
Example #25
Source File: Window.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the value of the {@code top} property.
 * @return the value of {@code top}
 */
@JsxGetter
public Object getTop() {
    if (top_ != NOT_FOUND) {
        return top_;
    }

    final WebWindow top = getWebWindow().getTopWindow();
    return top.getScriptableObject();
}
 
Example #26
Source File: DefaultJavaScriptExecutor.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Register a window with the eventLoop.
 * @param newWindow the new web window
 */
@Override
public void addWindow(final WebWindow newWindow) {
    final JavaScriptJobManager jobManager = newWindow.getJobManager();
    if (jobManager != null) {
        updateJobMangerList(jobManager);
        startThreadIfNeeded();
    }
}
 
Example #27
Source File: HTMLDocument.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
@Override
@JsxFunction({FF, FF68, FF60})
public void close() throws IOException {
    if (writeInCurrentDocument_) {
        LOG.warn("close() called when document is not open.");
    }
    else {
        final HtmlPage page = getPage();
        final URL url = page.getUrl();
        final StringWebResponse webResponse = new StringWebResponse(writeBuilder_.toString(), url);
        webResponse.setFromJavascript(true);
        writeInCurrentDocument_ = true;
        writeBuilder_.setLength(0);

        final WebClient webClient = page.getWebClient();
        final WebWindow window = page.getEnclosingWindow();
        // reset isAttachedToPageDuringOnload_ to trigger the onload event for chrome also
        if (window instanceof FrameWindow) {
            final BaseFrameElement frame = ((FrameWindow) window).getFrameElement();
            final ScriptableObject scriptable = frame.getScriptableObject();
            if (scriptable instanceof HTMLIFrameElement) {
                ((HTMLIFrameElement) scriptable).onRefresh();
            }
        }
        webClient.loadWebResponseInto(webResponse, window);
    }
}
 
Example #28
Source File: XMLDocument.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private static XmlPage createParserErrorXmlPage(final String message, final WebWindow webWindow)
        throws IOException {
    final String xml = "<parsererror xmlns=\"http://www.mozilla.org/newlayout/xml/parsererror.xml\">\n"
        + message + "\n"
        + "<sourcetext></sourcetext>\n"
        + "</parsererror>";

    final WebResponse webResponse = new StringWebResponse(xml, webWindow.getEnclosedPage().getUrl());

    return new XmlPage(webResponse, webWindow, false);
}
 
Example #29
Source File: XMLDocument.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance, with associated XmlPage.
 * @param enclosingWindow the window
 */
public XMLDocument(final WebWindow enclosingWindow) {
    if (enclosingWindow != null) {
        try {
            final XmlPage page = new XmlPage((WebResponse) null, enclosingWindow);
            setDomNode(page);
        }
        catch (final IOException e) {
            throw Context.reportRuntimeError("IOException: " + e);
        }
    }
}
 
Example #30
Source File: XMLHttpRequest4Test.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void setLocation() throws Exception {
    final String content =
          "<html>\n"
        + "  <head>\n"
        + "    <title>Page1</title>\n"
        + "    <script>\n"
        + "      var request;\n"
        + "      function testAsync() {\n"
        + "        request = new XMLHttpRequest();\n"
        + "        request.onreadystatechange = onReadyStateChange;\n"
        + "        request.open('GET', 'foo.xml', true);\n"
        + "        request.send('');\n"
        + "      }\n"
        + "      function onReadyStateChange() {\n"
        + "        if (request.readyState == 4) {\n"
        + "          window.location.href = 'about:blank';\n"
        + "        }\n"
        + "      }\n"
        + "    </script>\n"
        + "  </head>\n"
        + "  <body onload='testAsync()'>\n"
        + "  </body>\n"
        + "</html>";

    getMockWebConnection().setDefaultResponse("");
    final WebWindow window = loadPage(content).getEnclosingWindow();
    assertEquals(0, window.getWebClient().waitForBackgroundJavaScriptStartingBefore(1000));
    assertEquals("about:blank", window.getEnclosedPage().getUrl());
}