user2083712 user2083712 - 1 year ago 72
Java Question

Handling a popup window using selenium

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.

Answer Source

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.

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();

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

    for (String activeHandle : driver.getWindowHandles()) {
        if (!activeHandle.equals(mainWindowHandle)) {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download