Java Code Examples for com.gargoylesoftware.htmlunit.WebWindow#getEnclosedPage()

The following examples show how to use com.gargoylesoftware.htmlunit.WebWindow#getEnclosedPage() . 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: HtmlAnchor.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
@SuppressWarnings("unchecked")
public <P extends Page> P click(final Event event, final boolean ignoreVisibility) throws IOException {
    final boolean ctrl = event.isCtrlKey();
    WebWindow oldWebWindow = null;
    if (ctrl) {
        oldWebWindow = ((HTMLElement) event.getSrcElement()).getDomNodeOrDie()
                .getPage().getWebClient().getCurrentWindow();
    }

    P page = super.click(event, ignoreVisibility);

    if (ctrl) {
        page.getEnclosingWindow().getWebClient().setCurrentWindow(oldWebWindow);
        page = (P) oldWebWindow.getEnclosedPage();
    }

    return page;
}
 
Example 2
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 3
Source File: DomTreeWalkerTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void firstChild() throws Exception {
    final String html = "<html><head><script>\n"
            + "function test() {\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();
        final TreeWalker walker = page.createTreeWalker(page.getDocumentElement(),
                org.w3c.dom.traversal.NodeFilter.SHOW_ALL, null, true);
        assertThat(walker.firstChild(), instanceOf(HtmlHead.class));
    }
}
 
Example 4
Source File: DomNodeIteratorTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void nextNode() throws Exception {
    final String html = "<html><head><script>\n"
            + "function test() {\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();
        final NodeIterator iterator = page.createNodeIterator(page.getDocumentElement(), NodeFilter.SHOW_ALL, null,
                true);
        assertThat(iterator.nextNode(), instanceOf(HtmlHtml.class));
    }
}
 
Example 5
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 6
Source File: XMLDocument.java    From HtmlUnit-Android 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(FF)
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 7
Source File: HTMLDocumentTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
private void compatMode(final String doctype) throws Exception {
    final String html = doctype + "<html>\n"
        + "<head>\n"
        + "  <title>Test</title>\n"
        + "  <script>\n"
        + "  function test() {\n"
        + "    alert(document.compatMode);\n"
        + "  }\n"
        + "  </script>\n"
        + "</head>\n"
        + "<body onload='test()'>\n"
        + "</body>\n"
        + "</html>";

    final WebDriver driver = loadPageWithAlerts2(html);
    if (driver instanceof HtmlUnitDriver) {
        final WebWindow webWindow = getWebWindowOf((HtmlUnitDriver) driver);
        final HtmlPage page = (HtmlPage) webWindow.getEnclosedPage();
        assertEquals("BackCompat".equals(getExpectedAlerts()[0]), page.isQuirksMode());
    }
}
 
Example 8
Source File: History.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Pushes a state.
 * @param object the state object
 * @param title the title
 * @param url an optional URL
 */
@JsxFunction
public void pushState(final Object object, final String title, final String url) {
    final WebWindow w = getWindow().getWebWindow();
    try {
        URL newStateUrl = null;
        final HtmlPage page = (HtmlPage) w.getEnclosedPage();
        if (StringUtils.isNotBlank(url)) {
            newStateUrl = page.getFullyQualifiedUrl(url);
        }
        w.getHistory().pushState(object, newStateUrl);
    }
    catch (final IOException e) {
        Context.throwAsScriptRuntimeEx(e);
    }
}
 
Example 9
Source File: History.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Replaces a state.
 * @param object the state object
 * @param title the title
 * @param url an optional URL
 */
@JsxFunction
public void replaceState(final Object object, final String title, final String url) {
    final WebWindow w = getWindow().getWebWindow();
    try {
        URL newStateUrl = null;
        final HtmlPage page = (HtmlPage) w.getEnclosedPage();
        if (StringUtils.isNotBlank(url)) {
            newStateUrl = page.getFullyQualifiedUrl(url);
        }
        w.getHistory().replaceState(object, newStateUrl);
    }
    catch (final MalformedURLException e) {
        Context.throwAsScriptRuntimeEx(e);
    }
}
 
Example 10
Source File: History.java    From HtmlUnit-Android with Apache License 2.0 6 votes vote down vote up
/**
 * Pushes a state.
 * @param object the state object
 * @param title the title
 * @param url an optional URL
 */
@JsxFunction
public void pushState(final Object object, final String title, final String url) {
    final WebWindow w = getWindow().getWebWindow();
    try {
        URL newStateUrl = null;
        final HtmlPage page = (HtmlPage) w.getEnclosedPage();
        if (StringUtils.isNotBlank(url)) {
            newStateUrl = page.getFullyQualifiedUrl(url);
        }
        w.getHistory().pushState(object, newStateUrl);
    }
    catch (final IOException e) {
        Context.throwAsScriptRuntimeEx(e);
    }
}
 
Example 11
Source File: JavaScriptJobManagerImpl.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public int addJob(final JavaScriptJob job, final Page page) {
    final WebWindow w = getWindow();
    if (w == null) {
        /*
         * The window to which this job manager belongs has been garbage
         * collected. Don't spawn any more jobs for it.
         */
        return 0;
    }
    if (w.getEnclosedPage() != page) {
        /*
         * The page requesting the addition of the job is no longer contained by
         * our owner window. Don't let it spawn any more jobs.
         */
        return 0;
    }
    final int id = NEXT_JOB_ID_.getAndIncrement();
    job.setId(Integer.valueOf(id));

    synchronized (this) {
        scheduledJobsQ_.add(job);

        if (LOG.isDebugEnabled()) {
            LOG.debug("job added to queue");
            LOG.debug("    window is: " + w);
            LOG.debug("    added job: " + job.toString());
            LOG.debug("after adding job to the queue, the queue is: ");
            printQueue();
        }

        notify();
    }

    return id;
}
 
Example 12
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 13
Source File: HTMLElement.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/**
 * Implementation of the IE behavior #default#download.
 * @param uri the URI of the download source
 * @param callback the method which should be called when the download is finished
 * @see <a href="http://msdn.microsoft.com/en-us/library/ms531406.aspx">MSDN documentation</a>
 * @throws MalformedURLException if the URL cannot be created
 */
public void startDownload(final String uri, final Function callback) throws MalformedURLException {
    final WebWindow ww = getWindow().getWebWindow();
    final HtmlPage page = (HtmlPage) ww.getEnclosedPage();
    final URL url = page.getFullyQualifiedUrl(uri);
    if (!page.getUrl().getHost().equals(url.getHost())) {
        throw Context.reportRuntimeError("Not authorized url: " + url);
    }
    final JavaScriptJob job = BackgroundJavaScriptFactory.theFactory().
            createDownloadBehaviorJob(url, callback, ww.getWebClient());
    page.getEnclosingWindow().getJobManager().addJob(job, page);
}
 
Example 14
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 15
Source File: JavaScriptJobManagerImpl.java    From HtmlUnit-Android with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public int addJob(final JavaScriptJob job, final Page page) {
    final WebWindow w = getWindow();
    if (w == null) {
        /*
         * The window to which this job manager belongs has been garbage
         * collected. Don't spawn any more jobs for it.
         */
        return 0;
    }
    if (w.getEnclosedPage() != page) {
        /*
         * The page requesting the addition of the job is no longer contained by
         * our owner window. Don't let it spawn any more jobs.
         */
        return 0;
    }
    final int id = NEXT_JOB_ID_.getAndIncrement();
    job.setId(Integer.valueOf(id));

    synchronized (this) {
        scheduledJobsQ_.add(job);

        if (LOG.isDebugEnabled()) {
            LOG.debug("job added to queue");
            LOG.debug("    window is: " + w);
            LOG.debug("    added job: " + job.toString());
            LOG.debug("after adding job to the queue, the queue is: ");
            printQueue();
        }

        notify();
    }

    return id;
}
 
Example 16
Source File: WindowTest.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void parentAndTop() throws Exception {
    final String firstContent
        = "<html><head><title>First</title></head><body>\n"
        + "  <iframe name='left' src='" + URL_SECOND + "'></iframe>\n"
        + "</body></html>";
    final String secondContent
        = "<html><head><title>Second</title></head><body>\n"
        + "  <iframe name='innermost' src='" + URL_THIRD + "'></iframe>\n"
        + "</body></html>";
    final String thirdContent
        = "<html><head><title>Third</title><script>\n"
        + "function doAlert() {\n"
        + "  alert(parent != this);\n"
        + "  alert(top != this);\n"
        + "  alert(parent != top);\n"
        + "  alert(parent.parent == top);\n"
        + "  alert(parent.frames[0] == this);\n"
        + "  alert(top.frames[0] == parent);\n"
        + "}\n"
        + "</script></head>\n"
        + "<body><a id='clickme' onClick='doAlert()'>foo</a></body></html>";

    final WebClient webClient = getWebClient();
    final List<String> collectedAlerts = new ArrayList<>();
    webClient.setAlertHandler(new CollectingAlertHandler(collectedAlerts));

    final MockWebConnection webConnection = new MockWebConnection();
    webConnection.setResponse(URL_FIRST, firstContent);
    webConnection.setResponse(URL_SECOND, secondContent);
    webConnection.setResponse(URL_THIRD, thirdContent);

    webClient.setWebConnection(webConnection);

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

    final WebWindow innermostWebWindow = webClient.getWebWindowByName("innermost");
    final HtmlPage innermostPage = (HtmlPage) innermostWebWindow.getEnclosedPage();
    innermostPage.getHtmlElementById("clickme").click();

    assertNotSame(innermostWebWindow.getParentWindow(), innermostWebWindow);
    assertNotSame(innermostWebWindow.getTopWindow(), innermostWebWindow);
    assertNotSame(innermostWebWindow.getParentWindow(), innermostWebWindow.getTopWindow());
    assertSame(innermostWebWindow.getParentWindow().getParentWindow(), innermostWebWindow.getTopWindow());

    assertEquals(new String[] {"true", "true", "true", "true", "true", "true"}, collectedAlerts);
}
 
Example 17
Source File: XMLHttpRequest.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Sends the specified content to the server in an HTTP request and receives the response.
 * @param content the body of the message being sent with the request
 */
@JsxFunction
public void send(final Object content) {
    if (webRequest_ == null) {
        return;
    }
    prepareRequest(content);

    final Window w = getWindow();
    final WebWindow ww = w.getWebWindow();
    final WebClient client = ww.getWebClient();
    final AjaxController ajaxController = client.getAjaxController();
    final HtmlPage page = (HtmlPage) ww.getEnclosedPage();
    final boolean synchron = ajaxController.processSynchron(page, webRequest_, async_);
    if (synchron) {
        doSend(Context.getCurrentContext());
    }
    else {
        if (getBrowserVersion().hasFeature(XHR_FIRE_STATE_OPENED_AGAIN_IN_ASYNC_MODE)) {
            // quite strange but IE seems to fire state loading twice
            // in async mode (at least with HTML of the unit tests)
            setState(OPENED, Context.getCurrentContext());
        }

        // Create and start a thread in which to execute the request.
        final Scriptable startingScope = w;
        final ContextFactory cf = ((JavaScriptEngine) client.getJavaScriptEngine()).getContextFactory();
        final ContextAction<Object> action = new ContextAction<Object>() {
            @Override
            public Object run(final Context cx) {
                // KEY_STARTING_SCOPE maintains a stack of scopes
                @SuppressWarnings("unchecked")
                Deque<Scriptable> stack =
                        (Deque<Scriptable>) cx.getThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE);
                if (null == stack) {
                    stack = new ArrayDeque<>();
                    cx.putThreadLocal(JavaScriptEngine.KEY_STARTING_SCOPE, stack);
                }
                stack.push(startingScope);

                try {
                    doSend(cx);
                }
                finally {
                    stack.pop();
                }
                return null;
            }

            @Override
            public String toString() {
                return "XMLHttpRequest " + webRequest_.getHttpMethod() + " '" + webRequest_.getUrl() + "'";
            }
        };
        final JavaScriptJob job = BackgroundJavaScriptFactory.theFactory().
                createJavascriptXMLHttpRequestJob(cf, action);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Starting XMLHttpRequest thread for asynchronous request");
        }
        jobID_ = ww.getJobManager().addJob(job, page);
    }
}
 
Example 18
Source File: Window.java    From HtmlUnit-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes this window.
 * @param webWindow the web window corresponding to this window
 */
public void initialize(final WebWindow webWindow) {
    webWindow_ = webWindow;
    webWindow_.setScriptableObject(this);

    windowProxy_ = new WindowProxy(webWindow_);

    final Page enclosedPage = webWindow.getEnclosedPage();
    if (enclosedPage instanceof XmlPage) {
        document_ = new XMLDocument();
    }
    else {
        document_ = new HTMLDocument();
    }
    document_.setParentScope(this);
    document_.setPrototype(getPrototype(document_.getClass()));
    document_.setWindow(this);

    if (enclosedPage instanceof SgmlPage) {
        final SgmlPage page = (SgmlPage) enclosedPage;
        document_.setDomNode(page);

        final DomHtmlAttributeChangeListenerImpl listener = new DomHtmlAttributeChangeListenerImpl();
        page.addDomChangeListener(listener);

        if (page.isHtmlPage()) {
            ((HtmlPage) page).addHtmlAttributeChangeListener(listener);
            ((HtmlPage) page).addAutoCloseable(this);
        }
    }

    documentProxy_ = new DocumentProxy(webWindow_);

    navigator_ = new Navigator();
    navigator_.setParentScope(this);
    navigator_.setPrototype(getPrototype(navigator_.getClass()));

    screen_ = new Screen();
    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);

    console_ = new Console();
    ((Console) console_).setWebWindow(webWindow_);
    console_.setParentScope(this);
    ((Console) console_).setPrototype(getPrototype(((SimpleScriptable) console_).getClass()));

    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();
        }
    }
}
 
Example 19
Source File: JavaScriptExecutionJob.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
public void run() {
    final WebWindow w = window_.get();
    if (w == null) {
        // The window has been garbage collected! No need to execute, obviously.
        return;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Executing " + this + ".");
    }

    try {
        // Verify that the window is still open
        if (w.isClosed()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Enclosing window is now closed. Execution cancelled.");
            }
            return;
        }
        if (!w.getWebClient().containsWebWindow(w)) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Enclosing window is now closed. Execution cancelled.");
            }
            return;
        }

        // Verify that the current page is still available and a html page
        final Page enclosedPage = w.getEnclosedPage();
        if (enclosedPage == null || !enclosedPage.isHtmlPage()) {
            if (enclosedPage == null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("The page that originated this job doesn't exist anymore. Execution cancelled.");
                }
                return;
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("The page that originated this job is no html page ("
                            + enclosedPage.getClass().getName() + "). Execution cancelled.");
            }
            return;
        }

        runJavaScript((HtmlPage) enclosedPage);
    }
    finally {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Finished executing " + this + ".");
        }
    }
}
 
Example 20
Source File: HtmlAnchor.java    From HtmlUnit-Android with Apache License 2.0 3 votes vote down vote up
/**
 * Open this link in a new window, much as web browsers do when you shift-click a link or use the context
 * menu to open in a new window.
 *
 * It should be noted that even web browsers will sometimes not give the expected result when using this
 * method of following links. Links that have no real href and rely on JavaScript to do their work will
 * fail.
 *
 * @return the page opened by this link, nested in a new {@link com.gargoylesoftware.htmlunit.TopLevelWindow}
 * @throws MalformedURLException if the href could not be converted to a valid URL
 */
public final Page openLinkInNewWindow() throws MalformedURLException {
    final URL target = ((HtmlPage) getPage()).getFullyQualifiedUrl(getHrefAttribute());
    final String windowName = "HtmlAnchor.openLinkInNewWindow() target";
    final WebWindow newWindow = getPage().getWebClient().openWindow(target, windowName);
    return newWindow.getEnclosedPage();
}