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) {
    Set<String> handles = driver.getWindowHandles();
    if (handles.size() > 1) {
        for (String currentWindow : handles) {
    } 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?

  • I would take a look at the window title when you're switching windows. If you know the title you're looking for you can use that in a loop to stop of the correct window/tab.
    – Swagin9
    Commented Sep 7, 2016 at 20:45

2 Answers 2


How To Work with Multiple Windows

Some browsers might order windows by the order of being opened, other in alphabetic title order. Suggested solution is to get the list of active windows before new is opened, and compare them afterwards to find the new one.

Consider subscribing to the mailing list, for valuable tips and occasional webcasts.


This is the simple and best way to handle multiple window's.

public void Test(){
    String parentWindowHandler = driver.getWindowHandle(); // Store your parent window
    String subWindowHandler = null;

    Set<String> handles = driver.getWindowHandles(); // get all window handles
    Iterator<String> iterator = handles.iterator();
    while (iterator.hasNext()){
        subWindowHandler = iterator.next();
    driver.switchTo().window(subWindowHandler); // switch to popup window
                                                // perform operations on popup

    driver.switchTo().window(parentWindowHandler);  // switch back to parent window


For modal dialogue and popups Alerts

  • This assumes that window handles are returned in the order of opening. As you can see from the link in my answer, it is not always the case. Commented Sep 6, 2016 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.