Example usage for org.openqa.selenium WebDriver switchTo

List of usage examples for org.openqa.selenium WebDriver switchTo

Introduction

In this page you can find the example usage for org.openqa.selenium WebDriver switchTo.

Prototype

TargetLocator switchTo();

Source Link

Document

Send future commands to a different frame or window.

Usage

From source file:com.gargoylesoftware.htmlunit.javascript.host.Location2Test.java

License:Apache License

/**
 * @throws Exception if the test fails//  w  w w.  jav a 2s . co  m
 */
@Test
@Alerts("URLmenu.html")
public void refererHeaderWhenSettingFrameLocation() throws Exception {
    final String html = "<html><head><title>Frameset</title></head>\n" + "<frameset rows='20%,80%'>\n"
            + "  <frame src='menu.html' name='menu'>\n" + "  <frame src='' name='content'>\n"
            + "</frameset></html>";

    final String menu = "<html><head><title>Menu</title></head>\n" + "<body>\n"
            + "  <a id='link' href='content.html' target='content'>Link</a>\n"
            + "  <a id='jsLink' href='#' onclick=\"javascript:top.content.location='content.html';\">jsLink</a>\n"
            + "</body></html>";

    final String content = "<html><head><title>Content</title></head><body><p>content</p></body></html>";

    final MockWebConnection conn = getMockWebConnection();
    conn.setResponse(new URL(URL_FIRST, "menu.html"), menu);
    conn.setResponse(new URL(URL_FIRST, "content.html"), content);

    expandExpectedAlertsVariables(URL_FIRST);
    final WebDriver driver = loadPage2(html);

    assertEquals(2, conn.getRequestCount());

    // click an anchor with href and target
    driver.switchTo().frame(0);
    driver.findElement(By.id("link")).click();
    assertEquals(3, conn.getRequestCount());
    Map<String, String> lastAdditionalHeaders = conn.getLastAdditionalHeaders();
    assertEquals(getExpectedAlerts()[0], lastAdditionalHeaders.get("Referer"));

    // click an anchor with onclick which sets frame.location
    driver.findElement(By.id("jsLink")).click();
    assertEquals(4, conn.getRequestCount());
    lastAdditionalHeaders = conn.getLastAdditionalHeaders();
    assertEquals(getExpectedAlerts()[0], lastAdditionalHeaders.get("Referer"));
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.MessageChannelTest.java

License:Apache License

/**
 * @throws Exception if an error occurs// w w  w  .  ja  v a 2 s .c  o  m
 */
@Test
@Alerts("Message back from the IFrame, Hello from the main page!")
public void test() throws Exception {
    final String html = "<html><body>\n" + "<p>My body</p>\n" + "<iframe src='" + URL_SECOND
            + "' width='480' height='320'></iframe>\n" + "</body>\n" + "<script>\n"
            + "  if (window.MessageChannel) {\n" + "    var channel = new MessageChannel();\n"
            + "    var para = document.querySelector('p');\n"
            + "    var ifr = document.querySelector('iframe');\n" + "    var otherWindow = ifr.contentWindow;\n"
            + "    function iframeLoaded() {\n"
            + "      otherWindow.postMessage('Hello from the main page!', '*', [channel.port2]);\n" + "    }\n"
            + "    ifr.addEventListener('load', iframeLoaded, false);\n" + "    function handleMessage(e) {\n"
            + "      para.innerHTML = e.data;\n" + "    }\n" + "    channel.port1.onmessage = handleMessage;\n"
            + "  }\n" + "</script></html>";

    final String html2 = "<html><body>\n" + "  <p>iFrame body</p>\n" + "</body>\n" + "<script>\n"
            + "  if (window.MessageChannel) {\n" + "    var para = document.querySelector('p');\n"
            + "    onmessage = function(e) {\n" + "      para.innerHTML = e.data;\n"
            + "      e.ports[0].postMessage('Message back from the IFrame');\n" + "    }\n" + "  }\n"
            + "</script></html>";

    getMockWebConnection().setResponse(URL_SECOND, html2);
    final WebDriver driver = loadPage2(html);
    final List<String> actual = new ArrayList<>();
    actual.add(driver.findElement(By.tagName("p")).getText());
    driver.switchTo().frame(0);
    actual.add(driver.findElement(By.tagName("p")).getText());
    assertEquals(getExpectedAlerts(), actual);
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.Window2Test.java

License:Apache License

/**
 * Test for #1589 NullPointerException because of missing context.
 *
 * @throws Exception if the test fails/*from   w  w  w  . j  av  a  2s. c o m*/
 */
@Test
@Alerts("data: hello")
public void postMessageFromClick() throws Exception {
    final String html = "<html>\n" + "<head><title>foo</title></head>\n" + "<body>\n" + "<script>\n"
            + "  function receiveMessage(event) {\n" + "    alert('data: ' + event.data);\n" + "  }\n"

            + "  window.addEventListener('message', receiveMessage, false);\n" + "</script>\n"
            + "  <iframe id='myFrame' src='" + URL_SECOND + "'></iframe>\n" + "</body></html>";

    final String iframe = "<html><body>\n"
            + "<button id='clickme' onclick='top.postMessage(\"hello\", \"*\");'>Click me</a>\n"
            + "</body></html>";

    getMockWebConnection().setResponse(URL_SECOND, iframe);
    final WebDriver driver = loadPage2(html);
    driver.switchTo().frame("myFrame");
    driver.findElement(By.id("clickme")).click();

    verifyAlerts(driver, getExpectedAlerts());
}

From source file:com.gargoylesoftware.htmlunit.libraries.Sarissa0993Test.java

License:Apache License

/**
 * @throws Exception if an error occurs//w w  w  . j  a  v a2 s.c  o m
 */
@Test
@Alerts(DEFAULT = { "++++++++++++++++++", "+", "+", "+", "+++", "++", "++++F+++" }, CHROME = {
        "+++++++++++FF+++++", "+", "+", "+", "F++", "++",
        "++++F+++" }, IE = { "+++++++++++F++++++", "+", "+", "+", "FFF", "FF", "FFFFFFFF" })
// TODO [IE]XML sarissa 0.9.9.3 is not compatible with IE's new XML stuff
public void sarissa() throws Exception {
    startWebServer("src/test/resources/libraries/sarissa/0.9.9.3", null, null);
    final String url = URL_FIRST + "test/testsarissa.html";

    final WebDriver driver = getWebDriver();
    driver.get(url);

    driver.findElement(By.xpath("//button")).click();

    driver.switchTo().alert().dismiss();

    verify(driver, "SarissaTestCase", getExpectedAlerts()[0]);
    verify(driver, "XmlHttpRequestTestCase", getExpectedAlerts()[1]);
    verify(driver, "XMLSerializerTestCase", getExpectedAlerts()[2]);
    verify(driver, "DOMParserTestCase", getExpectedAlerts()[3]);
    verify(driver, "XMLDocumentTestCase", getExpectedAlerts()[4]);
    verify(driver, "XMLElementTestCase", getExpectedAlerts()[5]);
    verify(driver, "XSLTProcessorTestCase", getExpectedAlerts()[6]);
}

From source file:com.gargoylesoftware.htmlunit.selenium.TypingTest.java

License:Apache License

/**
 * A test.//  w w w.j  av  a 2s .  co m
 */
@Test
public void nonPrintableCharactersShouldWorkWithContentEditableOrDesignModeSet() {
    final WebDriver driver = getWebDriver("/rich_text.html");

    driver.switchTo().frame("editFrame");
    final WebElement element = driver.switchTo().activeElement();
    element.sendKeys("Dishy", Keys.BACK_SPACE, Keys.LEFT, Keys.LEFT);
    element.sendKeys(Keys.LEFT, Keys.LEFT, "F", Keys.DELETE, Keys.END, "ee!");

    assertEquals("Fishee!", element.getText());
}

From source file:com.gargoylesoftware.htmlunit.WebDriverTestCase.java

License:Apache License

/**
 * Gets the alerts collected by the driver.
 * Note: it currently works only if no new page has been loaded in the window
 * @param maxWaitTime the maximum time to wait to get the alerts (in millis)
 * @param driver the driver//from   w  w  w . j ava  2s  . c  om
 * @param alertsLength the expected length of Alerts
 * @return the collected alerts
 * @throws Exception in case of problem
 */
protected List<String> getCollectedAlerts(final long maxWaitTime, final WebDriver driver,
        final int alertsLength) throws Exception {
    final List<String> collectedAlerts = new ArrayList<>();

    final long maxWait = System.currentTimeMillis() + maxWaitTime;

    for (int i = 0; i < alertsLength; i++) {
        while (collectedAlerts.size() < alertsLength && System.currentTimeMillis() < maxWait) {
            try {
                final Alert alert = driver.switchTo().alert();
                collectedAlerts.add(alert.getText());
                alert.accept();
            } catch (final NoAlertPresentException e) {
                Thread.sleep(10);
            }
        }
    }

    return collectedAlerts;
}

From source file:com.gargoylesoftware.htmlunit.WebDriverTestCase.java

License:Apache License

/**
 * Release resources but DON'T close the browser if we are running with a real browser.
 * Note that HtmlUnitDriver is not cached by default, but that can be configured by {@link #isWebClientCached()}.
 *//*  w  w w.jav  a 2 s .c o  m*/
@After
@Override
public void releaseResources() {
    super.releaseResources();

    if (!isWebClientCached()) {
        if (webDriver_ != null) {
            webDriver_.quit();
        }
        assertTrue("There are still JS threads running after the test", getJavaScriptThreads().isEmpty());
    }

    if (useRealBrowser()) {
        synchronized (WEB_DRIVERS_REAL_BROWSERS) {
            final WebDriver driver = WEB_DRIVERS_REAL_BROWSERS.get(getBrowserVersion());
            if (driver != null) {
                try {
                    final String currentWindow = driver.getWindowHandle();

                    final Set<String> handles = driver.getWindowHandles();
                    // close all windows except the current one
                    handles.remove(currentWindow);

                    if (handles.size() > 0) {
                        for (final String handle : handles) {
                            try {
                                driver.switchTo().window(handle);
                                driver.close();
                            } catch (final NoSuchWindowException e) {
                                LOG.error("Error switching to browser window; quit browser.", e);
                                WEB_DRIVERS_REAL_BROWSERS.remove(getBrowserVersion());
                                WEB_DRIVERS_REAL_BROWSERS_USAGE_COUNT.remove(getBrowserVersion());
                                driver.quit();
                                return;
                            }
                        }

                        // we have to force WebDriver to treat the remaining window
                        // as the one we like to work with from now on
                        // looks like a web driver issue to me (version 2.47.2)
                        driver.switchTo().window(currentWindow);
                    }

                    driver.manage().deleteAllCookies();

                    // in the remaining window, load a blank page
                    driver.get("about:blank");
                } catch (final WebDriverException e) {
                    shutDownRealBrowsers();
                }
            }
        }
    }
}

From source file:com.github.wiselenium.factory.decorator.frame.FrameSwitcher.java

License:Open Source License

/**
 * Switches the driver to a frame, using its complete path.
 * //from w  w  w .ja va  2  s .  c om
 * @param framePath The frame path.
 * @since 0.3.0
 */
public static void switchToFramePath(List<String> framePath) {
    WebDriver driver = WiseContext.getDriver();
    driver.switchTo().defaultContent();
    for (String content : framePath)
        driver.switchTo().frame(content);
}

From source file:com.hotwire.test.steps.angular.AngularModelTemplate.java

License:Open Source License

@Override
public void clickCommentCardLink(String page) {
    if (page.equals("home")) {
        new AngularHomePage(getWebdriverInstance()).clickOlabLink();
    } else if (page.equals("results")) {
        new AngularHotelResultsPage(getWebdriverInstance()).clickOlabLink();
    } else if (page.equals("details")) {
        new AngularHotelDetailsPage(getWebdriverInstance()).clickOlabLink();
    } else {//  w  w w  .  java  2s  .  c om
        throw new UnimplementedTestException(page + ": not valid page id for this method.");
    }
    LOGGER.info(">>>>> Switching to comment card window <<<<<");
    // Need to switch to comment card window. Looping through set as it is not guaranteed what order will be
    // returned. Assuming there will only be 2 windows opened as anymore will be problematic.
    WebDriver webdriverInstance = getWebdriverInstance();
    String parentWindow = webdriverInstance.getWindowHandle();
    //String parentTitle = webdriverInstance.getTitle();
    for (String handle : webdriverInstance.getWindowHandles()) {
        LOGGER.info("Browser window handle: " + handle);
        if (!handle.equals(parentWindow)) {
            webdriverInstance.switchTo().window(handle);
            // Assume the window that doesn't have the parent title is the comment card.
            if (webdriverInstance.getTitle().equals("Comment card")) {
                LOGGER.info("Found comment card window.");
                break;
            }
        }
    }
}

From source file:com.hotwire.test.steps.application.ApplicationModelWebApp.java

License:Open Source License

@Override
public void submitCommentCard(String comment, int content, int design, int usability, int overall) {
    logger.info(">>>>> Switching to comment card window <<<<<");
    // Need to switch to comment card window. Looping through set as it is
    // not guaranteed what order will be
    // returned. Assuming there will only be 2 windows opened as anymore
    // will be problematic.
    WebDriver webdriverInstance = getWebdriverInstance();
    String parentWindow = webdriverInstance.getWindowHandle();
    // String parentTitle = webdriverInstance.getTitle();
    for (String handle : webdriverInstance.getWindowHandles()) {
        logger.info("Browser window handle: " + handle);
        if (!handle.equals(parentWindow)) {
            webdriverInstance.switchTo().window(handle);
            // Assume the window that doesn't have the parent title is the
            // comment card.
            if (webdriverInstance.getTitle().equals("Comment card")) {
                logger.info("Found comment card window.");
                break;
            }/* w  w  w .j a  v  a2 s .  co  m*/
        }
    }
    CommentCardPage commentCardPage = new CommentCardPage(getWebdriverInstance());
    commentCardPage.typeComment(comment);
    commentCardPage.rateContent(content);
    commentCardPage.rateDesign(design);
    commentCardPage.rateUsability(usability);
    commentCardPage.rateOverall(overall);
    commentCardPage.clickSubmitButton();

    logger.info("Comment card sent. Switching to parent browser window.");
    getWebdriverInstance().switchTo().window(getWebdriverInstance().getWindowHandles().toArray()[0].toString());
}