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