webdriver - 使用getWindowHandles()选择弹出窗口

时间:2014-03-03 08:45:47

标签: selenium window-handles

我正在尝试在弹出时切换焦点,但getWindowHandles()。size()只返回1个窗口。

如何确定我是否可以切换到弹出窗口?或弹出窗口不是我的情况下的新窗口

这是代码的一部分:

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

1 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

    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;
        }
    }