0

I have googled and looked at this site for reference but all the answers I came across did not provide a guaranteed way to switch to a specific window.


I am using Java with Selenium and I trying to find a guaranteed way to switch between two windows (where the second window is from clicking a link that produces a pop up).

driver.getWindowHandles() creates a Set object and since the Set interface does not provide any ordering guarantees, how will I be able to switch to a specific window?

What I currently have is this:

public static void switchToPopUpWindow(By by) {
    driver.findElement(by).click();
    Set<String> handles = driver.getWindowHandles();
    if (handles.size() > 1) {
        for (String currentWindow : handles) {
            driver.switchTo().window(currentWindow);
        }
    } else {
        logger.info("There is only one window open...");
    }
}

However, since the ordering is not guaranteed, it won't always land on the window that I want. How can I guarantee a switch to the pop up window?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Robben
  • 457
  • 2
  • 8
  • 20
  • Possible duplicate of [How to switch to the new browser window, which opens after click on the button](http://stackoverflow.com/questions/9588827/how-to-switch-to-the-new-browser-window-which-opens-after-click-on-the-button) – Saurabh Gaur Sep 02 '16 at 16:28

1 Answers1

0

To switch to a second window, switch with an handle different from the current one:

public static void switchToPopUpWindow(By by) {
    driver.findElement(by).click();

    String currentHandle = driver.getWindowHandle();
    Set<String> handles = driver.getWindowHandles();

    for (String handle : handles) {
        if (!handle.equals(currentHandle)) {
            driver.switchTo().window(handle);
            return;
        }
    }

    logger.info("There is only one window open...");
}
Florent B.
  • 41,537
  • 7
  • 86
  • 101