How to find a popup window if it does not have a name

22 October, 2014
When using Selenium 2.0 (WebDriver) you will sometimes find clicking a link opens a popup window. Before you can interact with the elements on the new window you need to switch to the new window.

If the new window has a name you can use the name to switch to the popup window:

        driver.switchTo().window(name);


However, if the window does not have a name you need to use the window handle. The problem is that every time you run the code the window handle will change. So you need to find the window handle for the popup window. To do this I use getWindowHandles() to find all the open windows, I click the link to open the new window. Next I use getWindowHandles() to get a second set of window handles. If I remove all the window handles of the first set from the second set I should end up with a set with only one element. That element will be the handle of the popup window.

Here is the code:
        String getPopupWindowHandle(WebDriver driver, WebElement link) {

           // get all the window handles before the popup window appears
           Set beforePopup = driver.getWindowHandles();

           // click the link which creates the popup window
           link.click();

           // get all the window handles after the popup window appears
           Set afterPopup = driver.getWindowHandles();

           // remove all the handles from before the popup window appears
           afterPopup.removeAll(beforePopup);

           // there should be only one window handle left
           if(afterPopup.size() == 1) {
            return (String)afterPopup.toArray()[0];
           }
           return null;
        }

To use this I simply call it with the WebElement which clicking opens the new window. You want to add some error handling to this but the basic idea of finding the popup window is here. To use the method I would use:

           String currentWindowHandle = driver.getWindowHandle();
           String popupWindowHandle = getPopupWindowHandle(driver, link);
           driver.switchTo().window(popupWindowHandle);
           // do stuff on the pop window
           // close the popup window
           driver.switchTo().window(currentWindowHandle)

No comments:

Post a Comment