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.virtusa.isq.vtaf.runtime.SeleniumTestBase.java

License:Apache License

/**
 * Check if the window is present in the context.
 * //from   ww  w . j  a va2s . c  o m
 * @param windowName
 *            : object name alias given by the user.
 * @param propertyname
 *            : Name of the object property
 * @param expectedvale
 *            : value expected for the given property
 * @param stopOnFailure
 *            :if <I> true </I> : stop the execution after the failure <br>
 *            if <I> false </I>: Continue the execution after the failure
 * */

private void checkWindowPresent(final String windowName, final String propertyname, final String expectedvale,
        final boolean stopOnFailure, final Object[] customError) {

    int counter = getRetryCount();
    boolean objectFound = false;
    WebDriver driver = getDriver();
    // String windowiden = "";

    // Getting the actual object identification from the object map
    String window = ObjectMap.getObjectSearchPath(windowName, locatorIdentifire);
    try {
        checkForNewWindowPopups();

        /*
         * START DESCRIPTION following for loop was added to make the
         * command more consistent try the command for give amount of time
         * (can be configured through class variable RETRY) command will be
         * tried for "RETRY" amount of times or untill command works. any
         * exception thrown within the tries will be handled internally.
         * 
         * can be exited from the loop under 2 conditions 1. if the command
         * succeeded 2. if the RETRY count is exceeded
         */
        while (counter > 0) {
            try {
                counter--;
                String currentWinHandle = driver.getWindowHandle();
                String targetWindow = getMatchingWindowFromCurrentWindowHandles(driver, window);
                driver.switchTo().window(currentWinHandle);
                if (expectedvale.equalsIgnoreCase(String.valueOf(targetWindow != null))) {

                    reportresult(true, "CHECK WINDOW PROPERTY:" + propertyname + "", "PASSED", "");
                } else {

                    /*String customErrorMessage = "";
                    if(customError !=null && !(customError[0].equals("null")||customError[0].equals("")) ) {
                            
                      for (int i=0;i<customError.length;i++){
                          customErrorMessage = customErrorMessage+customError[i].toString();
                      }
                      System.out.println(customErrorMessage);
                    }*/

                    if (customError != null && !(customError[0].equals("null") || customError[0].equals(""))) {
                        reportresult(true, "CHECK WINDOW PROPERTY:" + propertyname + "", "FAILED",
                                " Custom Error :" + generateCustomError(customError)
                                        + " System generated Error : Expected Property : " + propertyname
                                        + " expected value [ " + expectedvale + " ]does not match the actual ["
                                        + objectFound + "] for the window [" + windowName + "] [" + window
                                        + "]");
                        checkTrue(false, stopOnFailure, " Custom Error :" + generateCustomError(customError)
                                + " System generated Error : Expected Property : " + propertyname
                                + " expected value [ " + expectedvale + " ]does not match the actual ["
                                + objectFound + "] for the window [" + windowName + "] [" + window + "]");

                    } else {

                        reportresult(true, "CHECK WINDOW PROPERTY:" + propertyname + "", "FAILED",
                                "Expected Property : " + propertyname + " expected value [ " + expectedvale
                                        + " ]does not match the actual [" + objectFound + "] for the window ["
                                        + windowName + "] [" + window + "]");
                        checkTrue(false, stopOnFailure,
                                "Expected Property : " + propertyname + " expected value [ " + expectedvale
                                        + " ]does not match the actual [" + objectFound + "] for the window ["
                                        + windowName + "] [" + window + "]");
                    }

                }
                break;
            } catch (WebDriverException ex) {
                sleep(retryInterval);
                if (!(counter > 0)) {
                    reportresult(true, "CHECK WINDOW PROPERTY:" + propertyname + "", "FAILED",
                            "CHECK WINDOW PROPERTY  :Window (" + windowName + ") [" + window
                                    + "] is not accessible");
                    checkTrue(false, stopOnFailure, "CHECK WINDOW PROPERTY  :Window (" + windowName + ") ["
                            + window + "] is not accessible");
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        // if any exception is raised, report failure
        reportresult(true, "CHECK WINDOW PROPERTY:" + propertyname + "", "FAILED",
                "CHECK WINDOW PROPERTY  :Window (" + windowName + ") [" + window + "] is not accessible");
        checkTrue(false, stopOnFailure,
                "CHECK WINDOW PROPERTY  :Window (" + windowName + ") [" + window + "] is not accessible");

    }

}

From source file:com.volkhart.selenium.util.Window.java

License:Apache License

/**
 * Switches the WebDriver pointer to the specified window
 * /*from w ww .j a v  a2  s .c  o  m*/
 * Uses {@code String.contains()} to identify windows.
 * 
 * @param driver
 *            WebDriver being redirected
 * @param partialTitle
 *            A portion of the title of the window.
 */
public static void switchTo(WebDriver driver, String partialTitle) {
    Set<String> windows = driver.getWindowHandles();
    for (String s : windows) {
        driver.switchTo().window(s);
        if (driver.getTitle().toLowerCase().contains(partialTitle.toLowerCase()))
            break;
    }
}

From source file:com.westconcomster.MO365.java

public void mo365Order(WebDriver driver, String region) throws InterruptedException {

    String winHandleBefore = driver.getWindowHandle();
    Thread.sleep(10000);//from w ww  .  j  a va 2s .  c  o  m
    driver.findElement(By.xpath("//p[contains(.,'Buy Now')]")).click();

    //Select the customer
    for (String winHandle : driver.getWindowHandles()) {
        driver.switchTo().window(winHandle);
        System.out.println(">>>>>>>>>>inside child window");

        //Search for the customer
        Thread.sleep(5000);
        WebElement searchCust = driver.findElement(By.xpath("(.//*[@id='search_value'])[4]"));
        searchCust.clear();
        searchCust.sendKeys(Constants.companyName);
        Thread.sleep(5000);
        driver.findElement(By.xpath(
                ".//*[@id='customersList']/div[1]/ul/div[1]/div/div[2]/div/ecommerceselectable-customer/div/div[3]/div"))
                .click();

        //Select MO365
        WebElement searchProduct = driver.findElement(By.xpath("(.//*[@id='search_value'])[5]"));
        searchProduct.clear();
        searchProduct.sendKeys("MO365");
        Thread.sleep(2000);
        driver.findElement(By.xpath("//ecommerceselectable-product/div/div[3]/div/p")).click();
        (new WebDriverWait(driver, 60))
                .until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@name='quoteName']")))
                .sendKeys("LATAM_MO365_Order");

        Select dropdown = new Select(driver.findElement(By.name("root[contract][supportLevel]")));
        dropdown.selectByIndex(1);

        //Add reseller Margin
        driver.findElement(By.name("root[contract][resellermargin]")).clear();
        driver.findElement(By.name("root[contract][resellermargin]")).sendKeys("10");
        System.out.println(">>>>>>>Reseller Margin Added");
        driver.findElement(By.name("root[contract][billenduser]")).click();
        System.out.println(">>>>>>>>Bill End User");
        JavascriptExecutor jse = (JavascriptExecutor) driver;
        jse.executeScript("window.scrollBy(0,350)", "");
        Thread.sleep(5000);

        //select license
        MO365Licences mo365lic = new MO365Licences();
        mo365lic.mo365Licences(driver, region);
        //Select MO365 Add-ons
        MO365AddOns moadd = new MO365AddOns();
        moadd.mo365AddOns(driver, region);

        //Select Westcon Services
        MO365WestconServices mo365WS = new MO365WestconServices();
        mo365WS.mo365WestconServices(driver, region);

        //Total price
        WebElement price = (new WebDriverWait(driver, 60)).until(
                ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[text()[contains(.,'Total:')]]")));
        String totalAmt = price.getText().substring(price.getText().indexOf(":") + 1).trim();
        System.out.println(">>>>>>>>>>>TotalAmount" + totalAmt);

        //Click Next Button
        (new WebDriverWait(driver, 20).until(
                ExpectedConditions.visibilityOfElementLocated(By.xpath(".//button[contains(text(),'Next')]"))))
                        .click();
        Thread.sleep(10000);
        driver.findElement(By.xpath(".//button[contains(text(),'Submit Order')]")).click();

        //Add domain
        WebElement domain1 = (new WebDriverWait(driver, 30).until(ExpectedConditions
                .visibilityOfElementLocated(By.xpath("//input[@name='root[microsoft_info][domain_prefix]']"))));
        domain1.sendKeys(Constants.domian);
        domain1.sendKeys(Keys.TAB);
        Thread.sleep(10000);

        //Click on Submit Order
        WebElement submit = (new WebDriverWait(driver, 20).until(ExpectedConditions
                .visibilityOfElementLocated(By.xpath("//button[contains(text(),'Submit Order')]"))));
        submit.click();
        System.out.println(">>>>>>>>Order Submitted ");
        Thread.sleep(10000);

        //PO Number
        String orderNumber = driver.findElement(By.xpath(".//ecommercewizardstep[4]/section/div/div[2]/p"))
                .getText().replaceAll("\\D", "").trim();
        ;
        System.out.println(">>>>>>>>>>>Order number" + orderNumber);

        //Click on Close Button
        driver.findElement(By.xpath("//ecommercewizardstep[4]/section/div/div[2]/article/button[2]")).click();
        driver.switchTo().window(winHandleBefore);

        //*******Verify Order on Portal
        Thread.sleep(10000);
        String orderScreenOrder = driver.findElement(By.xpath(
                ".//*[@id='orders']/div/section[2]/div[1]/div[2]/div/div[2]/div/order/div[1]/div/div[1]/div[3]/div/div[1]/div[2]/div[2]"))
                .getText();
        System.out.println(">>>>>>>>>> OrderID" + orderScreenOrder);
        if (orderScreenOrder.equals(orderNumber)) {
            System.out.println(">>>>>> PASS <<<<<<< MO365 Order Created Successfully on portal");
        } else {
            System.out.println("Order FAILED");
        }
    }

}

From source file:core.Inject.java

License:Apache License

private void waitForAlert(String current_injection) {
    final WebDriver driver = Starter.getDriver();

    Alert alert = (new WebDriverWait(driver, 0)).until(new ExpectedCondition<Alert>() {
        public Alert apply(WebDriver d) {
            return driver.switchTo().alert();
        }/*from   w w w.j a  va  2s  .  co m*/
    });

    alert.accept();

    if (current_injection != null) {
        log(current_injection);

        if (bar != null)
            bar.setBroken();

        if (Starter.getParsedArgs().getStopFirstPositive()) {
            Starter.forceQuit();
        }
    }
}

From source file:crawl.CrawlThread.java

License:Open Source License

@Override
public void run() {
    WebDriver driver = new FirefoxDriver(); // The Firefox driver supports javascript 
    Autenticate.perform(driver, fb_email, fb_password);
    try {//from   ww  w. j  av  a 2 s.  com
        Thread.sleep(Globals.TIME_TO_LOGIN_IN_FB_MS);
    } catch (Exception ex) {
        System.out.println("InterruptedException in crawl.run()");
        ex.printStackTrace();
        System.exit(-1);
    }
    for (String post_id : post_list) {
        //OPEN NEW TAB
        WebElement body = driver.findElement(By.tagName("body"));
        body.sendKeys(Keys.CONTROL + "t");
        Tree post = new Tree(post_id, GLOBALS);
        boolean result = post.crawl(driver);
        if (result) {
            post.prune();
            post.print();
            post.printEdgeList();
        } else {
            body.sendKeys(Keys.CONTROL + "w");
        }
        //SWITCH TAB
        ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
        driver.switchTo().window(tabs.get(tabs.size() - 1));
    }
    driver.quit();
}

From source file:cuenen.raymond.svgplot.AbstractTestClass.java

License:CDDL license

/**
 * Retrieve the text of an alert window. This method also accepts the alert
 * (pressing OK)./*w  ww.ja  va  2  s .  c o m*/
 *
 * @param driver The WebDriver executing the test.
 * @throws NoAlertPresentException If the dialog cannot be found
 * @return The message text.
 */
protected String getAlert(WebDriver driver) throws NoAlertPresentException {
    Alert alert = driver.switchTo().alert();
    String text = alert.getText();
    alert.accept();
    return text;
}

From source file:de.knowwe.uitest.UITestUtils.java

License:Open Source License

/**
 * Loads the given article and waits for it to be loaded. If an alert pops up, it will be accepted.
 *
 * @param url         the url of the running wiki instance
 * @param articleName name of the article to be loaded
 * @param driver      the web driver/*from   w w w. ja  v  a  2 s  .  c  o  m*/
 */
public static void goToArticle(String url, String articleName, WebDriver driver) {
    driver.get(url + "/Wiki.jsp?page=" + articleName);
    try {
        driver.switchTo().alert().accept();
    } catch (NoAlertPresentException ignore) {
    }
}

From source file:de.learnlib.alex.data.entities.actions.web.AlertAcceptDismissActionTest.java

License:Apache License

@Before
public void before() {
    final WebSiteConnector webSiteConnector = Mockito.mock(WebSiteConnector.class);

    this.connectors = Mockito.mock(ConnectorManager.class);
    Mockito.when(connectors.getConnector(WebSiteConnector.class)).thenReturn(webSiteConnector);

    final WebDriver wd = Mockito.mock(WebDriver.class);
    Mockito.when(webSiteConnector.getDriver()).thenReturn(wd);

    this.targetLocator = Mockito.mock(WebDriver.TargetLocator.class);
    Mockito.when(wd.switchTo()).thenReturn(this.targetLocator);

    this.action = new AlertAcceptDismissAction();
}

From source file:de.learnlib.alex.data.entities.actions.web.AlertGetTextActionTest.java

License:Apache License

@Before
public void before() {
    this.webSiteConnector = Mockito.mock(WebSiteConnector.class);
    this.variableStore = new VariableStoreConnector();

    this.connectors = Mockito.mock(ConnectorManager.class);
    Mockito.when(connectors.getConnector(WebSiteConnector.class)).thenReturn(this.webSiteConnector);
    Mockito.when(connectors.getConnector(VariableStoreConnector.class)).thenReturn(this.variableStore);

    final Project project = new Project(1L);
    final Symbol symbol = new Symbol();
    symbol.setId(1L);//from  w  w  w.  j a  v  a  2  s  .c  o m
    symbol.setProject(project);

    this.action = new AlertGetTextAction();
    this.action.setVariableName(VARIABLE_NAME);
    this.action.setSymbol(symbol);

    this.targetLocator = Mockito.mock(WebDriver.TargetLocator.class);

    final WebDriver wd = Mockito.mock(WebDriver.class);
    Mockito.when(wd.switchTo()).thenReturn(this.targetLocator);
    Mockito.when(this.webSiteConnector.getDriver()).thenReturn(wd);
}

From source file:edu.samplu.common.WebDriverUtil.java

License:Educational Community License

protected static void selectFrameSafe(WebDriver driver, String locator) {
    try {// w w  w . j  av  a  2s. c om
        driver.switchTo().frame(locator);
    } catch (NoSuchFrameException nsfe) {
        // don't fail
    }
}