Java – use selenium to handle pop ups

I have a situation where I click on the link page to open a pop-up window When the pop-up window is opened, the focus is in the pop-up window and the main window is disabled I can't transfer the control to a pop-up window

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 cannot transfer the control from the parent window to the pop-up window I know the following orders

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

But it doesn't help much Please help me

Solution

This is the code that I need to close the following pop-up window and return to the main window Of course, it has been simplified for the purpose of this answer It holds the handle of the original (primary) window, so it can make a difference between other windows

It requires an explicit webdriverwait, because I did encounter the problem that the code runs before the window actually opens during development, so this may not be an 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);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>