Once, I created a utility class that managed window handling and kept track of all the open window handles. With this class, the project was able to handle up to 4 open browser popup windows and close them in a specific order.
Check out the project here.
There is definitely room for improvement, but here is an example method from that class:
/**
* Checks if WebDriver.getWindowHandles() returns any additional windows
* that are not currently in the allHandles cache. If a new window is found,
* it switches to that window and updates the allHandles cache.
*/
public static String handleNewWindow() {
String newHandle = "";
printHandles();
Set<String> updatedHandles = driver.getWindowHandles();
if (updatedHandles.size() < handleCache.size()) {
mainHandle = "";
LOGGER.info("Illegal state: A window was actually closed.");
throw new IllegalStateException("This method handleNewWindow is not suitable\n" +
"in this case. You probably want to use the updateHandleCache method.");
} else if (updatedHandles.size() == handleCache.size()) {
LOGGER.info("handleNewWindow() will do nothing because there are no new window handles.");
} else {
if (!updatedHandles.isEmpty()) {
for (String windowId : updatedHandles) {
if (!windowId.equals(mainHandle)) {
if (!handleCache.contains(windowId)) {
newHandle = windowId;
LOGGER.info("-- Open window handle: " + newHandle + " (new window)");
}
}
}
if (!newHandle.equals("")) {
LOGGER.info("Switching to new window.");
driver.switchTo().window(newHandle);
}
} else {
mainHandle = "";
throw new IllegalStateException("No browser window handles are open.");
}
}
handleCache = updatedHandles;
return newHandle;
}