Selenium | Find a particular window and close it via code

|
| By Webner

If multiple browser windows are opened, then find a particular window and close it by using web driver.

We can do so by using the following function:

public static void switchControlToSpecifiedWindow(WebDriver driver) {
    Iterator < String > windows = driver.getWindowHandles().iterator();
    while (windows.next()) {
        driver.switchTo().window(windows.next());
        String title = driver.getTitle();
        if (title.equals("abc")) {
            driver.close();
            break;
        }
    }
}

In the above function, first line, i.e. Iterator browsers = driver.getWindowHandles().iterator(); is used to get hold of all the browser windows. After getting the address of all the browser windows, we are finding the window with title ‘abc’ and closing it.

On the other hand suppose we have total 6 open browsers and want to close the 4th browser and don’t know the title of the browser then we can do by replacing above while block with the below for block:

for (int i = 0; i < 5; i++) {
    driver.switchTo().window(windows.next());
    if (i == 3) {
        driver.close();
        break;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *