When we create a new driver object a new browser window opens.This window has a window id. If we then go to a website ,on some sites mutiple windows open up.Each window has a unique id.
We can store all these window ids in a string set and can iterate through each of them and get their ids etc and from size of set also get total no of windows that are open.
And the set we get in Selenium is an ordered set by default. That means the first id will be of the main window and the second id will be of the first pop up and so on. We can go to each window in the set and close that window like we have done below
Set<String> winIds = driver.getWindowHandles();
System.out.println("The total no of windows open by default are "+winIds.size());
Iterator<String> it = winIds.iterator();
System.out.println("The id of dafault window open is " + it.next());
driver.get("https://naukri.com");
winIds = driver.getWindowHandles();
System.out.println("The total no of windows now open are "+winIds.size());
it = winIds.iterator();
while(it.hasNext()){
driver.switchTo().window(it.next());
driver.close();
}
//Go to default window in the end
driver.switchTo().defaultContent();
We can use the same code to switch between multiple tabs in the same window as well