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:selenium.webapps.termbrowser.TestTermBrowserTestCase.java

License:Open Source License

public String getPopupWindowBodyText(WebDriver driver) {
    String parentWindowHandler = driver.getWindowHandle();
    String subWindowHandler = null;
    Set<String> handles = driver.getWindowHandles();
    Iterator<String> iterator = handles.iterator();
    while (iterator.hasNext()) {
        subWindowHandler = iterator.next();
    }//from  ww w.j a  va 2s.  c o  m
    driver.switchTo().window(subWindowHandler);
    String bodyText = driver.findElement(By.tagName("body")).getText();
    driver.switchTo().window(parentWindowHandler);
    return bodyText;
}

From source file:selenium_tumblr_test.BasePage.java

License:Open Source License

public void clickThenWaitForPageReload(By elementBy, int seconds) {

    try {//from w w  w  .  j ava 2  s . c  o m

        // first get page source timestamp
        long timeStampValue1 = getPageSourceTimestamp();

        // find element & click it
        WebElement element = driver.findElement(elementBy);
        element.click();

        // now wait until element is no longer present or timeout
        try {
            (new FluentWait(driver)).withTimeout(seconds, TimeUnit.SECONDS)
                    .pollingEvery(pollInterval, TimeUnit.SECONDS)
                    .ignoring(java.util.NoSuchElementException.class).until(new Predicate<WebDriver>() {
                        @Override
                        public boolean apply(WebDriver driver) {
                            long timeStampValue2 = getPageSourceTimestamp();
                            return timeStampValue1 != timeStampValue2;
                        }
                    });
        } catch (TimeoutException timeoutException) {

        }

        // handle any alerts if they pop up
    } catch (org.openqa.selenium.UnhandledAlertException unhandledAlertException) {
        try {
            // try to switch to the alert dialog and accept it
            Alert alert = driver.switchTo().alert();
            alert.accept();
        } catch (org.openqa.selenium.NoAlertPresentException noAlertPresentException) {
            // alert may have gone away. if so, then ignore
        }
    }

}

From source file:testrunner.executor.URLStepExecutor.java

License:Apache License

/**
 * This method executes the step by loading the step's URL using the passed
 * driver./*  w w  w.  j a  v  a2  s  . com*/
 */
protected void doExecuteStep(Step step, WebDriver driver, StepResult result) throws Exception {
    driver.get(step.getUrl());
    try {
        if (driver.getTitle().matches("Certificate Error: Navigation Blocked")) {
            driver.get("javascript:document.getElementById('overridelink').click();");
            Thread.sleep(500);
            Alert alert = driver.switchTo().alert();
            alert.accept();
        }
    } catch (NoAlertPresentException e) {

    }
}

From source file:uk.co.blackpepper.common.driver.AbstractDriverTest.java

License:Apache License

private static OngoingStubbing<WebDriver> whenSwitchToWindow(WebDriver driver, String nameOrHandle) {
    TargetLocator locator = mock(TargetLocator.class);
    when(driver.switchTo()).thenReturn(locator);
    return when(locator.window(nameOrHandle));
}

From source file:utils.WebDriverUtils.java

public static void switchToWindow(WebDriver webDriver, String handle) {
    System.out.println("Switching to window " + handle);
    webDriver.switchTo().window(handle);
}

From source file:utils.WebDriverUtils.java

public static void switchFromIframe(WebDriver webDriver) {
    System.out.println("Switching from iframe");
    webDriver.switchTo().defaultContent();
}

From source file:utils.WebDriverUtils.java

public static void switchToIframeById(WebDriver webDriver, String iframeId) {
    System.out.println("Switching to iframe " + iframeId);
    webDriver.switchTo().frame(iframeId);
}

From source file:utils.WebDriverUtils.java

public static void switchToIframeByXpath(WebDriver webDriver, String iframeXpath) {
    System.out.println("Switching to iframe " + iframeXpath);
    webDriver.switchTo().frame(getElement(webDriver, iframeXpath));
}

From source file:utils.WebDriverUtils.java

public static void acceptJavaScriptAlert(WebDriver webDriver) {
    Alert alert = webDriver.switchTo().alert();
    alert.accept();
}

From source file:wsattacker.sso.openid.attacker.evaluation.attack.KeyConfusionAttack.java

License:Open Source License

@Attack(number = 1)
private AttackResult performSecondVariantOfKeyConfusionAttack() {
    OpenIdServerConfiguration.getAttackerInstance().setInterceptIdPResponse(true);
    OpenIdServerConfiguration.getAttackerInstance().setMethodGet(false);

    OpenIdServerConfiguration.getAnalyzerInstance().setInterceptIdPResponse(true);
    OpenIdServerConfiguration.getAnalyzerInstance().setMethodGet(false);

    OpenIdServerConfiguration.getAttackerInstance().setPerformAttack(true);

    String victimIdp = OpenIdServerConfiguration.getAnalyzerInstance().getXrdsConfiguration().getBaseUrl();

    AttackParameter opEndpointParameter = keeper.getParameter("openid.op_endpoint");
    opEndpointParameter.setAttackValueUsedForSignatureComputation(true);
    opEndpointParameter.setValidMethod(HttpMethod.DO_NOT_SEND);
    opEndpointParameter.setAttackMethod(HttpMethod.GET);
    opEndpointParameter.setAttackValue(victimIdp);

    String victimIdentity = OpenIdServerConfiguration.getAnalyzerInstance().getXrdsConfiguration()
            .getIdentity();/*from w  ww  .j  a  va  2s  .  c  o m*/

    AttackParameter claimedIdParameter = keeper.getParameter("openid.claimed_id");
    claimedIdParameter.setAttackValueUsedForSignatureComputation(true);
    claimedIdParameter.setValidMethod(HttpMethod.DO_NOT_SEND);
    claimedIdParameter.setAttackMethod(HttpMethod.GET);
    claimedIdParameter.setAttackValue(victimIdentity);

    AttackParameter identityParameter = keeper.getParameter("openid.identity");
    identityParameter.setAttackValueUsedForSignatureComputation(true);
    identityParameter.setValidMethod(HttpMethod.DO_NOT_SEND);
    identityParameter.setAttackMethod(HttpMethod.GET);
    identityParameter.setAttackValue(victimIdentity);

    // include modified parameter in signature
    AttackParameter sigParameter = keeper.getParameter("openid.sig");
    sigParameter.setValidMethod(HttpMethod.DO_NOT_SEND);
    sigParameter.setAttackMethod(HttpMethod.GET);

    // copy log entries before login
    List<RequestLogEntry> logEntriesBeforeLogin = new ArrayList<>(RequestLogger.getInstance().getEntryList());

    LoginResult loginResultAttacker = serviceProvider.login(ServiceProvider.User.ATTACKER);

    WebDriver driver = SeleniumBrowser.getWebDriver();
    JavascriptExecutor jse = (JavascriptExecutor) driver;
    String url = serviceProvider.getUrl();
    jse.executeScript("var win = window.open('" + url + "');");

    List<String> windowhandles = new ArrayList<>(driver.getWindowHandles());
    driver.switchTo().window(windowhandles.get(1));

    LoginResult loginResultVictim = serviceProvider.login(ServiceProvider.User.VICTIM);

    driver.switchTo().window(windowhandles.get(0));

    List<WebElement> links = driver.findElements(By.tagName("a"));
    links.get(1).click();

    /* determines the log entries of the current login procedure:
       logEntries = logEntriesAfterLogin - logEntriesBeforeLogin
       (subtraction of sets) */
    List<RequestLogEntry> logEntriesAfterLogin = RequestLogger.getInstance().getEntryList();
    List<RequestLogEntry> logEntries = (List<RequestLogEntry>) CollectionUtils.subtract(logEntriesAfterLogin,
            logEntriesBeforeLogin);

    // invert order of log - should be chronological
    Collections.reverse(logEntries);

    loginResultAttacker.setScreenshot(SeleniumBrowser.takeScreenshot());
    loginResultAttacker.setLogEntries(logEntries);

    boolean success = serviceProvider.determineAuthenticatedUser(driver.getPageSource(),
            driver.getCurrentUrl()) == User.VICTIM;
    Result result = success ? Result.SUCCESS : Result.FAILURE;
    Interpretation interpretation = success ? Interpretation.CRITICAL : Interpretation.PREVENTED;

    if (loginResultAttacker.hasDirectVerification()) {
        result = Result.NOT_PERFORMABLE;
        interpretation = Interpretation.NEUTRAL;
    }

    assert isSignatureValid(loginResultAttacker) : "Signature is not valid!";

    // close second window
    driver.switchTo().window(windowhandles.get(1)).close();
    driver.switchTo().window(windowhandles.get(0));

    return new AttackResult("Second Variant of Key Confusion", loginResultAttacker, result, interpretation);
}