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.ecofactor.qa.automation.insite.page.RoleManagementImpl.java

License:Open Source License

/**
 * <p>/*from  ww w . j a  v a 2  s . c  o  m*/
 * Click on Save button and wait for alert to be popped.The verify the page is redirected
 * properly.
 * </p>
 * @param driver the driver
 * @param roleName the role name
 */
private void saveAndVerifyRole(final WebDriver driver, final String roleName) {

    DriverConfig.setLogString(
            "Click on save link and verify the alert is popped, finally check the page is re-directed properly.",
            true);
    final WebElement saveElement = retrieveElementByLinkText(driver, "Save", SHORT_TIMEOUT);
    saveElement.click();

    (new WebDriverWait(driver, LONG_TIMEOUT + LONG_TIMEOUT)).until(ExpectedConditions.alertIsPresent());
    DriverConfig.setLogString("click ok on alert message.", true);
    logger.info("click ok on alert message.");
    DriverConfig.setLogString("Alert Message :" + driver.switchTo().alert().getText(), true);
    waitUntil(FIVE_SECS);
    driver.switchTo().alert().accept();

    /*
     * retrieveElementByLinkText(driver, "First", SHORT_TIMEOUT); Assert.assertEquals(true,
     * driver.getCurrentUrl().contains("roles.html"), "Url doesn't contains roles.html");
     */
    smallWait();
    logger.info("find role name element is displayed.");
    DriverConfig.setLogString("find role name element is displayed.", true);
    isDisplayedById(driver, roleConfig.get(ROLE_NAME), SHORT_TIMEOUT);
    DriverConfig.setLogString("Enter role name as " + roleName, true);
    driver.findElement(By.id(roleConfig.get(ROLE_NAME))).sendKeys(roleName);
    DriverConfig.setLogString("check if find button is displayed & click it.", true);
    final WebElement findButtonElement = retrieveElementByAttributeValue(driver, TAG_INPUT, ATTR_VALUE,
            roleConfig.get(FIND_BUTTON));
    findButtonElement.click();
    DriverConfig.setLogString("check if search result is displayed.", true);
    confirmSearchResultValue(driver, roleName);
}

From source file:com.ecofactor.qa.automation.util.PageUtil.java

License:Open Source License

/**
 * Close alert.//from   www.  j a  va  2 s.  c o m
 *
 * @param driver the driver
 */
public static void closeAlert(WebDriver driver) {

    try {
        WebDriverWait wait = new WebDriverWait(driver, SHORT_TIMEOUT);
        if (wait.until(ExpectedConditions.alertIsPresent()) != null) {
            driver.switchTo().alert().accept();
        }
    } catch (Exception e) {
        // ignore any exception
    }
}

From source file:com.evidon.areweprivateyet.Crawler.java

License:Open Source License

private void killPopups(String baseWindow, WebDriver driver) {
    // close any new popups.
    for (String handle : driver.getWindowHandles()) {
        if (!handle.equals(baseWindow)) {
            WebDriver popup = driver.switchTo().window(handle);
            log("\tClosing popup: " + popup.getCurrentUrl());
            popup.close();/*from   w w w .  jav a 2  s .  c  o m*/

            // TODO: need to see if this breaks when there is a modal.
        }
    }

    driver.switchTo().window(baseWindow);
}

From source file:com.evidon.areweprivateyet.Crawler.java

License:Open Source License

public Crawler(String namedProfile) throws Exception {
    loadSiteList();//from www.  ja va2s  .c o m

    int sleepTime = (namedProfile.equals("baseline") ? 10 : 5);
    boolean started = false;
    String baseWindow = "";

    FirefoxProfile profile = new ProfilesIni().getProfile(namedProfile);
    //profile.setPreference("webdriver.load.strategy", "fast");

    WebDriver driver = new FirefoxDriver(profile);

    driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
    driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
    driver.manage().timeouts().setScriptTimeout(40, TimeUnit.SECONDS);

    // figure out where the fucking profile is. wow!
    String profileDir = getDriverProfile();

    log("Crawling started for " + namedProfile);

    int count = 0;
    for (String url : urls) {
        if (!started) {
            // Original window handle to be used as base. Used so we can close all other popups.  
            baseWindow = driver.getWindowHandle();
            started = true;
        }

        count++;
        log("\t" + count + ". navigating to: " + url);

        CrawlusInterruptus ci = new CrawlusInterruptus(60);
        try {
            ci.start();

            try {
                // Confirm handling for one of those super fucking annoying "Are you sure you wonna go anywhere else?"
                driver.switchTo().alert().accept();
                log("\tAccepted a navigate away modal");
            } catch (Exception e) {
            }

            driver.get("http://" + url);

            // WTF, why would their own fucking wait not work?!?
            // new WebDriverWait(driver, 5 * 1000);
        } catch (TimeoutException te) {
            handleTimeout(baseWindow, url, driver);
        } catch (org.openqa.selenium.UnhandledAlertException me) {
            log("\tModal exception caused by previous site?");

            // Retry current site.
            try {
                driver.get("http://" + url);
            } catch (TimeoutException te) {
                handleTimeout(baseWindow, url, driver);
            }
        } finally {
            ci.interrupt();
        }

        try {
            Thread.sleep(sleepTime * 1000);
        } catch (InterruptedException e) {
        }

        killPopups(baseWindow, driver);
    }

    // 4th party does not know when the crawl is over, so we send a trip signal by navigating to the "last" domain
    try {
        driver.get("http://www.josesignanini.com");
    } catch (TimeoutException te) {
    }
    try {
        Thread.sleep(60 * 1000);
    } catch (InterruptedException e) {
    }

    // copy the fourthparty database out.
    FileUtils.copyFile(new File(profileDir + "/fourthparty.sqlite"),
            new File(path + "/fourthparty-" + namedProfile + ".sqlite"));

    driver.quit();
    log("Crawling completed for " + namedProfile);

    recordLog(namedProfile);
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlFrame2Test.java

License:Apache License

/**
 * Was failing as of HtmlUnit-2.11./*  w w  w .  j a v a2 s.co  m*/
 * @see <a href="sourceforge.net/p/htmlunit/bugs/1443/">Bug #1443</a>
 * @throws Exception if the test fails
 */
@Test
@Alerts("foo")
public void onloadInNavigatedFrame() throws Exception {
    final String html = "<html><head><title>first</title></head>\n" + "<frameset cols='20%,80%'>\n"
            + "  <frame src='frame1.html' id='frame1'>\n" + "</frameset></html>";

    final String firstHtml = "<html><body>\n" + "<a id='a1' href='frame2.html'>hello</a>\n" + "</body></html>";

    final String secondHtml = "<html><body onload='alert(\"foo\")'></body></html>";

    final MockWebConnection webConnection = getMockWebConnection();
    webConnection.setResponse(new URL(URL_FIRST, "frame1.html"), firstHtml);
    webConnection.setResponse(new URL(URL_FIRST, "frame2.html"), secondHtml);

    final WebDriver driver = loadPage2(html);
    driver.switchTo().frame(0);

    driver.findElement(By.id("a1")).click();

    verifyAlerts(driver, getExpectedAlerts());
}

From source file:com.gargoylesoftware.htmlunit.html.HtmlInlineFrame2Test.java

License:Apache License

/**
 * Test, the right frame is used for a target, even if some frames
 * have the same name./* www . j av  a  2 s  .co m*/
 *
 * @throws Exception if the test fails
 */
@Test
public void targetResolution() throws Exception {
    final String framesContent = "<html><head><title>Top Page</title></head>\n"
            + "<body><div id='content'>Body of top frame</div>\n"
            + "  <iframe src='left.html' id='id-left' name='left'></iframe>\n"
            + "  <iframe src='right.html' id='id-right' name='right'></iframe>\n" + "</body>\n" + "</html>";

    final String rightFrame = "<html><head><title>Right Frame</title></head>\n"
            + "<body><div id='content'>Body of right frame</div></body>\n" + "</html>";

    final String leftFrame = "<html><head><title>Left Frame</title></head>\n" + "<body>\n"
            + "  <div id='content'>Body of left frame</div>\n"
            + "  <a id='link' name='link' href='new_inner.html' target='right'>Click link</a>\n"
            + "  <iframe id='id-inner' name='right' width='100' height='100' src='inner.html'></iframe>\n"
            + "</body>\n" + "</html>";

    final String innerFrame = "<html><head><title>Inner Frame</title></head>\n"
            + "<body><div id='content'>Body of inner frame</div></body>\n" + "</html>";

    final String newInnerFrame = "<html><head><title>New inner Frame</title></head>\n"
            + "<body><div id='content'>Body of new inner frame</div></body>\n" + "</html>";

    final String baseUrl = URL_FIRST.toString();

    final URL leftFrameUrl = new URL(baseUrl + "left.html");
    final URL rightFrameUrl = new URL(baseUrl + "right.html");
    final URL innerFrameURL = new URL(baseUrl + "inner.html");
    final URL newInnerFrameURL = new URL(baseUrl + "new_inner.html");

    final MockWebConnection webConnection = getMockWebConnection();
    webConnection.setResponse(leftFrameUrl, leftFrame);
    webConnection.setResponse(rightFrameUrl, rightFrame);
    webConnection.setResponse(innerFrameURL, innerFrame);
    webConnection.setResponse(newInnerFrameURL, newInnerFrame);

    final WebDriver driver = loadPage2(framesContent);

    // top frame
    assertEquals("Top Page", driver.getTitle());
    assertEquals("Body of top frame", driver.findElement(By.id("content")).getText());

    // left frame
    driver.switchTo().frame("id-left");
    assertEquals("Body of left frame", driver.findElement(By.id("content")).getText());
    // inner frame
    driver.switchTo().frame("id-inner");
    assertEquals("Body of inner frame", driver.findElement(By.id("content")).getText());
    // right frame
    driver.switchTo().defaultContent();
    driver.switchTo().frame("id-right");
    assertEquals("Body of right frame", driver.findElement(By.id("content")).getText());

    // clicking on a link which contains a target 'right'. But this target frame is defined two times.
    driver.switchTo().defaultContent();
    driver.switchTo().frame("id-left");
    driver.findElement(By.id("link")).click();

    // left frame
    driver.switchTo().defaultContent();
    driver.switchTo().frame("id-left");
    assertEquals("Body of left frame", driver.findElement(By.id("content")).getText());
    // inner frame
    driver.switchTo().frame("id-inner");
    assertEquals("Body of new inner frame", driver.findElement(By.id("content")).getText());
    // right frame
    driver.switchTo().defaultContent();
    driver.switchTo().frame("id-right");
    assertEquals("Body of right frame", driver.findElement(By.id("content")).getText());
}

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

License:Apache License

/**
 * Regression test for issue 1568./*w  w w .j ava2 s .c  o m*/
 * @throws Exception if the test fails
 */
@Test
@Alerts(DEFAULT = { "[object HTMLBodyElement]", "http://localhost:12345/#",
        "http://localhost:12345/#" }, IE11 = { "null", "http://localhost:12345/#",
                "http://localhost:12345/#" }, IE8 = { "[object]", "http://localhost:12345/#",
                        "http://localhost:12345/#" }, CHROME = { "[object HTMLBodyElement]",
                                "[object HTMLBodyElement]", "[object HTMLBodyElement]" })
public void activeElement_iframe() throws Exception {
    final String html = "<html>\n" + "<head></head>\n" + "<body>\n"

            + "  <a id='insert' " + "onclick=\"insertText("
            + "'<html><head></head><body>first frame text</body></html>');\" href=\"#\">"
            + "insert text to frame</a>\n" + "  <a id= 'update' " + "onclick=\"insertText("
            + "'<html><head></head><body>another frame text</body></html>');\" href=\"#\">"
            + "change frame text again</a><br>\n"
            + "  <iframe id='innerFrame' name='innerFrame' src='frame1.html'></iframe>\n"

            + "  <script>\n" + "    alert(document.activeElement);\n"

            + "    function insertText(text) {\n" + "      with (innerFrame.document) {\n" + "        open();\n"
            + "        writeln(text);\n" + "        close();\n" + "      }\n"
            + "      alert(document.activeElement);\n" + "    }\n" + "  </script>\n" + "</body>\n" + "</html>";

    getMockWebConnection().setResponse(new URL("http://example.com/frame1.html"), "");

    final WebDriver driver = loadPage2(html);

    driver.findElement(By.id("insert")).click();
    driver.switchTo().frame(driver.findElement(By.id("innerFrame")));
    assertEquals("first frame text", driver.findElement(By.tagName("body")).getText());

    driver.switchTo().defaultContent();
    driver.findElement(By.id("update")).click();
    driver.switchTo().frame(driver.findElement(By.id("innerFrame")));
    assertEquals("another frame text", driver.findElement(By.tagName("body")).getText());

    assertEquals(getExpectedAlerts(), getCollectedAlerts(driver));
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.dom.Document2Test.java

License:Apache License

/**
 * Regression test for issue 1568.//from   w w w .j  av a2s.  com
 * @throws Exception if the test fails
 */
@Test
@Alerts(DEFAULT = { "[object HTMLBodyElement]", "http://localhost:12345/#", "http://localhost:12345/#" }, IE = {
        "null", "http://localhost:12345/#", "http://localhost:12345/#" })
@NotYetImplemented(IE)
public void activeElement_iframe() throws Exception {
    final String html = "<html>\n" + "<head></head>\n" + "<body>\n"

            + "  <a id='insert' " + "onclick=\"insertText("
            + "'<html><head></head><body>first frame text</body></html>');\" href=\"#\">\n"
            + "insert text to frame</a>\n" + "  <a id= 'update' " + "onclick=\"insertText("
            + "'<html><head></head><body>another frame text</body></html>');\" href=\"#\">\n"
            + "change frame text again</a><br>\n"
            + "  <iframe id='innerFrame' name='innerFrame' src='frame1.html'></iframe>\n"

            + "  <script>\n" + "    alert(document.activeElement);\n"

            + "    function insertText(text) {\n" + "      with (innerFrame.document) {\n" + "        open();\n"
            + "        writeln(text);\n" + "        close();\n" + "      }\n"
            + "      alert(document.activeElement);\n" + "    }\n" + "  </script>\n" + "</body>\n" + "</html>";

    getMockWebConnection().setResponse(new URL("http://example.com/frame1.html"), "");

    final WebDriver driver = loadPage2(html);
    verifyAlerts(driver, getExpectedAlerts()[0]);

    driver.findElement(By.id("insert")).click();
    verifyAlerts(driver, getExpectedAlerts()[1]);

    driver.switchTo().frame(driver.findElement(By.id("innerFrame")));
    assertEquals("first frame text", driver.findElement(By.tagName("body")).getText());

    driver.switchTo().defaultContent();
    driver.findElement(By.id("update")).click();
    verifyAlerts(driver, getExpectedAlerts()[2]);

    driver.switchTo().frame(driver.findElement(By.id("innerFrame")));
    assertEquals("another frame text", driver.findElement(By.tagName("body")).getText());
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.html.HTMLAnchorElement2Test.java

License:Apache License

private void javascriptTarget(final String target, final int newWindows, final String[] expectedAlerts)
        throws Exception {
    final String html = "<html>\n" + "<head><title>main</title></head>\n" + "<body>\n"
            + "  <iframe id='testFrame' src='" + URL_SECOND + "'></iframe>\n" + "</body></html>";

    final String secondHtml = "<html>\n" + "<head><title>inner</title></head>\n" + "<body>\n"
            + "  <a id='tester' " + target
            + " href='javascript: try { alert(document.title); } catch(e) { alert(e); }'>no href</a>\n"
            + "</body>\n" + "</html>";

    getMockWebConnection().setResponse(URL_SECOND, secondHtml);

    setExpectedAlerts(expectedAlerts);//from  ww w . ja va  2 s .c  om
    final WebDriver driver = loadPage2(html);

    driver.switchTo().frame("testFrame");
    assertEquals(1, driver.getWindowHandles().size());
    driver.findElement(By.id("tester")).click();
    assertEquals(1 + newWindows, driver.getWindowHandles().size());

    verifyAlerts(driver, getExpectedAlerts());
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocumentWrite2Test.java

License:Apache License

/**
 * Partial regression test for bug 2921851: use opener URL as base URL
 * for resolution of relative URLs in document.write.
 * @throws Exception if the test fails/*from   w  w w .ja v a 2s.c o  m*/
 */
@Test
@Alerts(DEFAULT = { "2", "URLfoo" }, IE = { "1", "URL" })
@NotYetImplemented(IE)
public void urlResolutionInWriteForm() throws Exception {
    final String html = "<html><head>\n" + "<script>\n" + "function test() {\n"
            + "  var newWin = window.open('', 'myPopup', '');\n" + "  var d = newWin.document;\n"
            + "  d.write('<html><body><form action=foo method=post><input type=submit id=it></form></body></html>');\n"
            + "  d.close();\n" + "}\n" + "</script></head>\n" + "<body onload='test()'>\n" + "</body></html>";

    final int startCount = getMockWebConnection().getRequestCount();
    expandExpectedAlertsVariables(URL_FIRST);

    getMockWebConnection().setDefaultResponse("");
    final WebDriver driver = loadPage2(html);
    driver.switchTo().window("myPopup");
    driver.findElement(By.id("it")).click();

    assertEquals(Integer.parseInt(getExpectedAlerts()[0]),
            getMockWebConnection().getRequestCount() - startCount);
    assertEquals(getExpectedAlerts()[1], getMockWebConnection().getLastWebRequest().getUrl());
}