Example usage for org.openqa.selenium WebDriver getWindowHandles

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

Introduction

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

Prototype

Set<String> getWindowHandles();

Source Link

Document

Return a set of window handles which can be used to iterate over all open windows of this WebDriver instance by passing them to #switchTo() .

Usage

From source file:com.java.AppTestType_18_11_2015.java

public void APPROVEUSER(WebDriver driver, String fieldText, String value) {
    //To Handle Approve User Popup 
    //FieldText---The User's FullName   and Value-----OK or Cancel
    try {/*from  www . j  a  va2s.  c  om*/
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver.findElement(By.linkText(fieldText)).click();
        Thread.sleep(2000);
        String parentwindow = driver.getWindowHandle();
        if (value.equalsIgnoreCase("OK")) {
            driver.findElement(By.linkText("Approve User")).click();
            Thread.sleep(2000);

            driver.switchTo().alert().accept();

            for (String win : driver.getWindowHandles()) {
                driver.switchTo().window(win);
                try {
                    driver.switchTo().alert().accept();
                } catch (NoAlertPresentException e) {
                    Robot robot = new Robot();
                    robot.keyPress(KeyEvent.VK_SPACE);
                    Thread.sleep(3000);
                }

            }
            Thread.sleep(20000);
            driver.switchTo().window(parentwindow);
            WebDriverWait wait = new WebDriverWait(driver, 20);
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("id_frm_Email_Address")));
            String Email = driver.findElement(By.id("id_frm_Email_Address")).getText();
            driver.findElement(By.name("email")).sendKeys(EMAIL);
            driver.findElement(By.xpath("//input[@value='Search']")).click();

            String Type = driver.findElement(By.xpath("//input[@value='Search']/following::tr[3]/td[6]"))
                    .getText();
            String Active_Status = driver
                    .findElement(By.xpath("//input[@value='Search']/following::tr[3]/td[6]")).getText();
            String BStatus = driver.findElement(By.xpath("//input[@value='Search']/following::tr[3]/td[6]"))
                    .getText();
            String SStatus = driver.findElement(By.xpath("//input[@value='Search']/following::tr[3]/td[6]"))
                    .getText();

            if (Type.equalsIgnoreCase("L") && Active_Status.equalsIgnoreCase("Active")
                    && BStatus.equalsIgnoreCase("Approved") && SStatus.equalsIgnoreCase("Approved")) {
                resultDetails.setFlag(true);
            }
        } else if (value.equalsIgnoreCase("CANCEL")) {
            driver.findElement(By.linkText("Approve User")).click();
            Thread.sleep(2000);
            //Robot robot = new Robot();
            // Simulate SPACE KEY press to click on OK button
            //robot.keyPress(KeyEvent.VK_ESCAPE);
            driver.switchTo().alert().dismiss();
            resultDetails.setFlag(true);

        }

    }

    catch (Exception e) {

        e.printStackTrace();
        resultDetails.setFlag(false);
    }
}

From source file:com.liferay.cucumber.selenium.WebDriverHelper.java

License:Open Source License

public static String getLocation(WebDriver webDriver) throws Exception {
    List<Exception> exceptions = new ArrayList<>();

    for (int i = 0; i < 3; i++) {
        FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {

            @Override/*  w  ww . j av a  2  s  .  co  m*/
            public String call() throws Exception {
                return _webDriver.getCurrentUrl();
            }

            private Callable<String> _init(WebDriver webDriver) throws Exception {

                _webDriver = webDriver;

                return this;
            }

            private WebDriver _webDriver;

        }._init(webDriver));

        Thread thread = new Thread(futureTask);

        thread.start();

        try {
            String location = futureTask.get(PropsValues.TIMEOUT_EXPLICIT_WAIT, TimeUnit.SECONDS);

            return location;
        } catch (CancellationException ce) {
            exceptions.add(ce);
        } catch (ExecutionException ee) {
            exceptions.add(ee);
        } catch (InterruptedException ie) {
            exceptions.add(ie);
        } catch (TimeoutException te) {
            exceptions.add(te);
        } finally {
            thread.interrupt();
        }

        System.out.println("WebDriverHelper#getLocation(WebDriver):");
        System.out.println(webDriver.toString());

        Set<String> windowHandles = webDriver.getWindowHandles();

        for (String windowHandle : windowHandles) {
            System.out.println(windowHandle);
        }
    }

    if (!exceptions.isEmpty()) {
        throw new Exception(exceptions.get(0));
    } else {
        throw new TimeoutException();
    }
}

From source file:com.liferay.cucumber.selenium.WebDriverHelper.java

License:Open Source License

public static void selectWindow(WebDriver webDriver, String windowID) {
    Set<String> windowHandles = webDriver.getWindowHandles();

    if (windowID.equals("name=undefined")) {
        String title = webDriver.getTitle();

        for (String windowHandle : windowHandles) {
            WebDriver.TargetLocator targetLocator = webDriver.switchTo();

            targetLocator.window(windowHandle);

            if (!title.equals(webDriver.getTitle())) {
                return;
            }//from w ww.ja v  a2  s. co m
        }

        TestCase.fail("Unable to find the window ID \"" + windowID + "\"");
    } else if (windowID.equals("null")) {
        WebDriver.TargetLocator targetLocator = webDriver.switchTo();

        targetLocator.window(_defaultWindowHandle);
    } else {
        String targetWindowTitle = windowID;

        if (targetWindowTitle.startsWith("title=")) {
            targetWindowTitle = targetWindowTitle.substring(6);
        }

        for (String windowHandle : windowHandles) {
            WebDriver.TargetLocator targetLocator = webDriver.switchTo();

            targetLocator.window(windowHandle);

            if (targetWindowTitle.equals(webDriver.getTitle())) {
                return;
            }
        }

        TestCase.fail("Unable to find the window ID \"" + windowID + "\"");
    }
}

From source file:com.liferay.faces.test.selenium.browser.internal.BrowserDriverImpl.java

License:Open Source License

@Override
public Set<String> getWindowIds() {

    WebDriver webDriver = getWebDriver();

    return webDriver.getWindowHandles();
}

From source file:com.liferay.faces.test.selenium.expectedconditions.WindowOpened.java

License:Open Source License

@Override
public Boolean apply(WebDriver webDriver) {

    Set<String> windowHandles = webDriver.getWindowHandles();
    int numberOfWindows = windowHandles.size();

    return (initialNumberOfWindows + 1) == numberOfWindows;
}

From source file:com.mgmtp.jfunk.web.JFunkWebDriverEventListener.java

License:Apache License

/**
 * Saves the currently displayed browser window. The page title is used for the filename -
 * preceded by some identifying information (thread, counter). Pages of the same type are
 * collected inside the same subdirectory. The subdirectory uses
 * {@link SaveOutput#getIdentifier()} for its name. If an alert is present, saving is not
 * supported and thus skipped./*from  w w w  .  j a va  2  s .  c o  m*/
 *
 * @param action
 *            the event which triggered to save the page. Will be included in the filename.
 * @param triggeredBy
 *            the object which triggered the event (e.g. a button or a link)
 */
protected void savePage(final WebDriver driver, final String action, final String triggeredBy) {
    try {
        // this updates the driver's window handles, so a subsequent call to
        // getWindowHandle() fails if the window no longer exists
        driver.getWindowHandles();
        driver.getWindowHandle();
    } catch (NoSuchWindowException ex) {
        // Window is already closed. Saving the page could cause problems, e. g.
        // ChromeDriver ould hang.
        return;
    }
    File moduleArchiveDir = moduleArchiveDirProvider.get();
    if (moduleArchiveDir == null) {
        return;
    }

    if (config.getBoolean(JFunkConstants.ARCHIVE_DO_NOT_SAVE_WHEN_ALERT, false)) {
        try {
            // Saving the page does not work if an alert is present
            driver.switchTo().alert();
            log.trace("Cannot save page. Alert is present.");
            return;
        } catch (NoAlertPresentException ex) {
            // ignore
        } catch (UnsupportedOperationException ex) {
            // ignore
            // HtmlUnit does not support alerts
        } catch (Exception ex) {
            // ignore
        }
    }

    for (SaveOutput saveOutput : SaveOutput.values()) {
        boolean saveSwitch = saveOutputMap.get(saveOutput);
        if (!saveSwitch) {
            // Saving is disabled by property
            continue;
        }

        File f = null;
        try {
            f = dumpFileCreatorProvider.get().createDumpFile(
                    new File(moduleArchiveDir, saveOutput.getIdentifier()), saveOutput.getExtension(),
                    driver.getCurrentUrl(), action);

            if (f == null) {
                return;
            }

            switch (saveOutput) {
            case HTML:
                StringBuilder html = new StringBuilder();
                html.append("<!-- Requested URL: ");
                html.append(driver.getCurrentUrl());
                html.append(" -->");
                html.append(IOUtils.LINE_SEPARATOR);
                html.append(driver.getPageSource());
                writeStringToFile(f, html.toString(), "UTF-8");
                copyFile(f, new File(moduleArchiveDir, JFunkConstants.LASTPAGE_HTML));
                log.trace("Saving page: filename={}, action={}, trigger={}, response={}", f.getName(), action,
                        triggeredBy, driver.getCurrentUrl());
                break;
            case PNG:
                if (driver instanceof TakesScreenshot) {
                    File tmpFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
                    if (tmpFile != null) {
                        copyFile(tmpFile, f);
                        log.trace("Saving page: filename={}, action={}, trigger={}, response={}", f.getName(),
                                action, triggeredBy, driver.getCurrentUrl());
                        deleteQuietly(tmpFile);
                    }
                }
                break;
            case HTML_VALIDATION:
                /*
                 * JFunkWebDriver.getPageSource() doesn't return the complete page source
                 * e.g. DOCTYPE is missing. Therefore we are using a more complicated way to
                 * retrieve the "real" page source. However, this only works when using
                 * HtmlUnitDriver.
                 */
                if (WebDriverUtils.isHtmlUnitDriver(driver)) {
                    String content = ((HtmlPage) WebDriverUtils.getHtmlUnitDriverWebClient(driver)
                            .getCurrentWindow().getEnclosedPage()).getWebResponse().getContentAsString();
                    writeStringToFile(f, content, "UTF-8");
                    HtmlValidatorUtil.validateHtml(f.getParentFile(), config, f);
                }
                break;
            default:
                throw new IllegalStateException("unknown enum constant");
            }
        } catch (Exception ex) {
            log.error("Could not save file: {}. {}", f, ex.getMessage());
            return;
        }
    }
}

From source file:com.pentaho.ctools.utils.ElementHelper.java

License:Apache License

/**
 * This function shall wait for the new window display.
 * The code check if there is more than one window in the list. In the
 * beginning we only have the main window.
 *
 * @param driver//from ww  w.  ja va2 s .  c om
 */
public void WaitForNewWindow(WebDriver driver) {
    this.log.debug("WaitForNewWindow::Enter");

    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(30, TimeUnit.SECONDS).pollingEvery(500,
            TimeUnit.MILLISECONDS);

    wait.until(new ExpectedCondition<Boolean>() {

        @Override
        public Boolean apply(WebDriver d) {
            return d.getWindowHandles().size() != 1;
        }
    });

    this.log.debug("WaitForNewWindow::Exit");
}

From source file:com.pentaho.ctools.utils.ElementHelper.java

License:Apache License

/**
 * This method shall select a new window that has opened and return the handle for the parent window.
 * /*from www . j  a va 2s  . c  o m*/
 * The handle should be stored in a string so we can go back to the parent window afterwards
 * using the SelectParentWindow method
 * 
 * @param driver
 * @return parentWindow
 */
public String SelectNewWindow(final WebDriver driver) {
    String parentWindowHandle = driver.getWindowHandle();
    Set<String> listWindows = driver.getWindowHandles();
    WaitForNewWindow(driver);
    listWindows = driver.getWindowHandles();
    // Get the windowHandler of the new open window
    Iterator<String> iterWindows = listWindows.iterator();
    while (iterWindows.hasNext()) {
        String windowHandle = iterWindows.next();
        if (windowHandle.equals(parentWindowHandle) == false) {
            driver.switchTo().window(windowHandle);
            break;
        }
    }
    return parentWindowHandle;
}

From source file:com.seleniumtests.it.driver.TestBrowserSnapshot.java

License:Apache License

/**
 * Check that when an error occurs when communicating with driver, a desktop capture is taken 
 *///from   w w  w.  ja  v a  2 s  .  c o m
@Test(groups = { "it" })
public void testMultipleWindowsCaptureWithError() {
    DriverTestPage.link.click();

    WebDriver mockedDriver = spy(driver);
    ScreenshotUtil screenshotUtil = spy(new ScreenshotUtil(mockedDriver));

    when(mockedDriver.getWindowHandles()).thenThrow(WebDriverException.class);

    List<ScreenShot> screenshots = screenshotUtil.capture(Target.PAGE, ScreenShot.class, true, false);

    Assert.assertEquals(screenshots.size(), 1);
    verify(screenshotUtil).captureDesktop();

}

From source file:com.smartqa.utils.WebDriverUtils.java

License:Apache License

/**
 * close web drvier properly/*from w  ww . j  av a 2 s .  co m*/
 * 
 * @param driver
 */
public static void closeWebDriver(WebDriver driver) {
    if (driver == null)
        return;

    try {
        String current = driver.getWindowHandle();
        Set<String> otherWins = driver.getWindowHandles();
        for (String winId : otherWins)
            if (winId.equals(current))
                continue;
            else
                driver.switchTo().window(winId).close();
    } catch (Exception ex) {
        LOG.warn("Error happen when close web driver: " + ex.getMessage());
    } finally {
        try {
            driver.quit();
        } catch (Exception ex) {
        }
    }
}