Tuesday, July 3, 2012

Switching between Windows and POP ups

*******************************************************
Select the Popup, it doesnt have the Name in webdriver
*******************************************************
static String getPopupWindowHandle(WebDriver driver, WebElement link) {

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

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

    // get all the window handles after the popup window appears
    Set<String> 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;
}

Usage as like below

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)