Example usage for org.openqa.selenium WebDriver getWindowHandle

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

Introduction

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

Prototype

String getWindowHandle();

Source Link

Document

Return an opaque handle to this window that uniquely identifies it within this driver instance.

Usage

From source file:com.thoughtworks.selenium.webdriven.commands.Windows.java

License:Apache License

public void selectFrame(WebDriver driver, String locator) {
    if ("relative=top".equals(locator)) {
        driver.switchTo().defaultContent();
        lastFrame.remove(driver.getWindowHandle());
        return;/*  ww  w .  ja v  a 2  s .c o  m*/
    }

    if (locator.startsWith("index=")) {
        try {
            int index = Integer.parseInt(locator.substring("index=".length()));
            lastFrame.put(driver.getWindowHandle(), locator);
            driver.switchTo().frame(index);
            return;
        } catch (NumberFormatException e) {
            throw new SeleniumException(e.getMessage(), e);
        } catch (NoSuchFrameException e) {
            throw new SeleniumException(e.getMessage(), e);
        }
    }

    if (locator.startsWith("id=")) {
        locator = locator.substring("id=".length());
    } else if (locator.startsWith("name=")) {
        locator = locator.substring("name=".length());
    }

    try {
        lastFrame.put(driver.getWindowHandle(), locator);
        driver.switchTo().frame(locator);
    } catch (NoSuchFrameException e) {
        throw new SeleniumException(e.getMessage(), e);
    }
}

From source file:com.thoughtworks.selenium.webdriven.commands.Windows.java

License:Apache License

private void selectWindowWithTitle(WebDriver driver, String title) {
    String current = driver.getWindowHandle();
    for (String handle : driver.getWindowHandles()) {
        driver.switchTo().window(handle);
        if (title.equals(driver.getTitle())) {
            return;
        }//from  w ww  .  j av  a  2s  .co  m
    }

    driver.switchTo().window(current);
    throw new SeleniumException("Unable to select window with title: " + title);
}

From source file:com.thoughtworks.selenium.webdriven.commands.Windows.java

License:Apache License

/**
 * Selects the only <code>_blank</code> window. A window open with <code>target='_blank'</code>
 * will have a <code>window.name = null</code>.
 * <p/>//from   w ww  . ja  va2 s.  co m
 * <p>
 * This method assumes that there will only be one single <code>_blank</code> window and selects
 * the first one with no name. Therefore if for any reasons there are multiple windows with
 * <code>window.name = null</code> the first found one will be selected.
 * <p/>
 * <p>
 * If none of the windows have <code>window.name = null</code> the last selected one will be
 * re-selected and a {@link SeleniumException} will be thrown.
 * 
 * @throws NoSuchWindowException if no window with <code>window.name = null</code> is found.
 */
public void selectBlankWindow(WebDriver driver) {
    String current = driver.getWindowHandle();
    // Find the first window without a "name" attribute
    List<String> handles = new ArrayList<String>(driver.getWindowHandles());
    for (String handle : handles) {
        // the original window will never be a _blank window, so don't even look at it
        // this is also important to skip, because the original/root window won't have
        // a name either, so if we didn't know better we might think it's a _blank popup!
        if (handle.equals(originalWindowHandle)) {
            continue;
        }
        driver.switchTo().window(handle);
        String value = (String) ((JavascriptExecutor) driver).executeScript("return window.name;");
        if (value == null || "".equals(value)) {
            // We found it!
            return;
        }
    }
    // We couldn't find it
    driver.switchTo().window(current);
    throw new SeleniumException("Unable to select window _blank");
}

From source file:com.thoughtworks.selenium.webdriven.Windows.java

License:Apache License

public void selectFrame(WebDriver driver, String locator) {
    if ("relative=top".equals(locator)) {
        driver.switchTo().defaultContent();
        lastFrame.remove(driver.getWindowHandle());
        return;//from  www . j ava 2  s .c  o  m
    }

    if ("relative=up".equals(locator)) {
        driver.switchTo().parentFrame();
        lastFrame.put(driver.getWindowHandle(), locator);
        return;
    }

    if (locator.startsWith("index=")) {
        try {
            int index = Integer.parseInt(locator.substring("index=".length()));
            lastFrame.put(driver.getWindowHandle(), locator);
            driver.switchTo().frame(index);
            return;
        } catch (NumberFormatException e) {
            throw new SeleniumException(e.getMessage(), e);
        } catch (NoSuchFrameException e) {
            throw new SeleniumException(e.getMessage(), e);
        }
    }

    if (locator.startsWith("id=")) {
        locator = locator.substring("id=".length());
    } else if (locator.startsWith("name=")) {
        locator = locator.substring("name=".length());
    }

    try {
        lastFrame.put(driver.getWindowHandle(), locator);
        driver.switchTo().frame(locator);
    } catch (NoSuchFrameException e) {
        throw new SeleniumException(e.getMessage(), e);
    }
}

From source file:com.vaadin.testbench.TestBenchDriverTest.java

@Test
public void testTestBenchDriverActsAsProxy() {
    FirefoxDriver mockDriver = createMock(FirefoxDriver.class);
    mockDriver.close();//from  www .  ja  v a2 s .c  om
    expectLastCall().once();
    WebElement mockElement = createNiceMock(WebElement.class);
    expect(mockDriver.findElement(isA(By.class))).andReturn(mockElement);
    List<WebElement> elements = Arrays.asList(mockElement);
    expect(mockDriver.findElements(isA(By.class))).andReturn(elements);
    mockDriver.get("foo");
    expectLastCall().once();
    expect(mockDriver.getCurrentUrl()).andReturn("foo");
    expect(mockDriver.getPageSource()).andReturn("<html></html>");
    expect(mockDriver.getTitle()).andReturn("bar");
    expect(mockDriver.getWindowHandle()).andReturn("baz");
    Set<String> handles = new HashSet<String>();
    expect(mockDriver.getWindowHandles()).andReturn(handles);
    Options mockOptions = createNiceMock(Options.class);
    expect(mockDriver.manage()).andReturn(mockOptions);
    Navigation mockNavigation = createNiceMock(Navigation.class);
    expect(mockDriver.navigate()).andReturn(mockNavigation);
    mockDriver.quit();
    expectLastCall().once();
    expect(((JavascriptExecutor) mockDriver).executeScript(anyObject(String.class))).andStubReturn(true);
    TargetLocator mockTargetLocator = createNiceMock(TargetLocator.class);
    expect(mockDriver.switchTo()).andReturn(mockTargetLocator);
    replay(mockDriver);

    // TestBenchDriverProxy driver = new TestBenchDriverProxy(mockDriver);
    WebDriver driver = TestBench.createDriver(mockDriver);
    driver.close();
    By mockBy = createNiceMock(By.class);
    assertTrue(driver.findElement(mockBy) instanceof TestBenchElementCommands);
    assertTrue(driver.findElements(mockBy).get(0) instanceof TestBenchElementCommands);
    driver.get("foo");
    assertEquals("foo", driver.getCurrentUrl());
    assertEquals("<html></html>", driver.getPageSource());
    assertEquals("bar", driver.getTitle());
    assertEquals("baz", driver.getWindowHandle());
    assertEquals(handles, driver.getWindowHandles());
    assertEquals(mockOptions, driver.manage());
    assertEquals(mockNavigation, driver.navigate());
    driver.quit();
    assertEquals(mockTargetLocator, driver.switchTo());

    verify(mockDriver);
}

From source file:com.vilt.minium.WebElementsDriver.java

License:Apache License

/**
 * Instantiates a new web elements driver.
 *
 * @param wd the wd/*from w ww.  java  2 s .  c o  m*/
 * @param factory the factory
 * @param configuration the configuration
 */
protected WebElementsDriver(WebDriver wd, WebElementsFactory factory, Configuration configuration) {
    this(wd, factory, configuration, wd.getWindowHandle());
}

From source file:com.virtusa.isq.vtaf.runtime.SeleniumTestBase.java

License:Apache License

/**
 * Check if the window is present in the context.
 * //from   w ww. j a v  a 2s  . 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.westconcomster.MO365.java

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

    String winHandleBefore = driver.getWindowHandle();
    Thread.sleep(10000);//w w w  .  j a v  a 2 s . 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:edu.uga.cs.clickminer.test.WindowStateTest.java

License:Open Source License

/**
 * <p>windowStateTest_1.</p>
 *
 * @throws java.lang.InterruptedException if any.
 */// w w w . j a  va 2  s .  co m
public static void windowStateTest_1() throws InterruptedException {
    WebDriver wdriver = new FirefoxDriver();
    wdriver.get("http://www.google.com");
    WindowState bstate = new WindowState(null, wdriver, wdriver.getWindowHandle());

    Thread.sleep(2000); // not the best way to do this, but quick and dirty
    System.out.println(bstate.getPageHash());
}

From source file:edu.uga.cs.clickminer.test.WindowStateTest.java

License:Open Source License

/**
 * <p>windowStateTest_2.</p>
 *
 * @throws java.lang.Exception if any.//from   ww  w  .  j  a v a  2 s.  com
 */
public static void windowStateTest_2() throws Exception {
    long poll_interval = 10000;
    WebDriver wdriver = new FirefoxDriver(TestUtils.createProxyConfig());
    ProxyClient pclient = new ProxyClient("127.0.0.1", 8888);
    wdriver.get("http://www.google.com");

    WindowState bstate = new WindowState(pclient, wdriver, wdriver.getWindowHandle());
    Thread.sleep(2000); // not the best way to do this, but quick and dirty

    while (!bstate.isResting()) {
        try {
            System.out.println(bstate);
            Thread.sleep(poll_interval);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    System.out.println("The browser is in a resting state.");
    System.out.println(bstate);
    bstate.reset();
    wdriver.quit();
}