使用 selenium 处理弹出窗口

2022-01-20 00:00:00 selenium selenium-webdriver popup java

我有一种情况,点击链接网页会打开一个弹出窗口.弹出窗口打开后,焦点在弹出窗口中,主窗口被禁用.而且我无法将控件转移到弹出窗口.请看下面的代码.

I have a circumstance in which clicking a link webpage opens a popup window. And after the popup window opens the focus is in the popup window and master window is disabled. And i am unable to get the control transferred to the popup window. Please have a look at the following code.

driver.findElement(By.linkText("Click me")).click();// when this line of code is reached then a popup window opens.

System.out.println("After Clicking me"); // After the popup window opens this line of code is never executed.

我无法将控件从父窗口转移到弹出窗口.我知道以下命令.

I am unable to transfer the control from parent window to popup window. I am aware of the following command.

driver.switchTo().window("popup window");

但它没有多大帮助.请帮帮我.

But its not helping much. please help me.

推荐答案

这是我在需要处理以下弹出窗口时使用的代码,关闭它并返回我的主窗口.当然,为了这个答案,它已经被简化了.它维护原始窗口(主)的句柄,因此它可以在其他窗口之间产生差异.

This is a code i use when i need to work with a following pop-up window, close it and go back to my main window. Of course it has been simplified for the purpose of this answer. It maintains a handle of the original window (main) so it can make a difference between the others.

它需要一个显式的 WebDriverWait,因为我在开发过程中确实遇到了代码在窗口实际打开之前运行的问题,所以这可能不是一个理想的条件,

It requires an explicit WebDriverWait because i did have problems during development that code got run before the window actually got open, so this might not be a ideal condition,

function manipulatePopUp(final WebDriver driver, final WebDriverWait wait) {
    final String mainWindowHandle = driver.getWindowHandle();
    driver.findElement(By.id("linkThatOpensPopUp")).click();

    wait.until(new ExpectedConditions<Boolean>() {
        @Override
        public Boolean apply(WebDriver d) {
            return (d.getWindowHandles().size() != 1);
        }
    });

    for (String activeHandle : driver.getWindowHandles()) {
        if (!activeHandle.equals(mainWindowHandle)) {
            driver.switchTo().window(activeHandle);
        }
    }

    driver.close();
    driver.switchTo().window(mainWindowHandle);
}

相关文章