Search code examples
seleniumwindow-handles

webdriver - select popup with getWindowHandles()


I'm trying to switch focus on popup when appears but getWindowHandles().size() is returning just 1 window.

how to determine if I can switch to popup? or popup is not a new windows in my case

here is a part of code:

String parentWindowHandlerP = driver.getWindowHandle(); // save ID parent window
String subWindowHandlerP = null;

    // action to call popup
    (new WebDriverWait(driver, 5)).until(ExpectedConditions.elementToBeClickable(By.id("pt1:pt_region0:2:pt1:ilov1::lovIconId"))).click();

    Set<String> handlesP = driver.getWindowHandles(); // get all windows
    Iterator<String> iteratorP = handlesP.iterator();
    while (iteratorP.hasNext()) {
        subWindowHandlerP = iteratorP.next();
    }
    // popup operations     
    driver.findElement(By.id("pt1:pt_region0:2:pt1:t1:_afrFltrc6::content")).sendKeys(Keys.RETURN);
    driver.findElement(By.id("pt1:pt_region0:2:pt1:ilov1_afrLovDialogId::ok")).click();

    driver.switchTo().window(parentWindowHandlerP); // back na parent window

Solution

  • You can use something like this:

        String parentWindowHandlerP = driver.getWindowHandle(); 
        // action to call popup
        (new WebDriverWait(driver, 5)).until(ExpectedConditions.elementToBeClickable(By.id("pt1:pt_region0:2:pt1:ilov1::lovIconId"))).click();
    
        while (driver.getWindowHandles().size() < 2) {
            Thread.sleep(500);
        }
        Set<String> handles = driver.getWindowHandles();
        for (String windowHandle : handles) {
            if (!windowHandle.equals(parentWindowHandlerP)) {
                driver.switchTo().window(windowHandle);
                break;
            }
        }