I have a solution which I had used on IE(never tried on other browser).
Suppose you have 5 IE windows opened, perform the iterator on all the windows and save the window iterators in a variable which will be an Array:
String parentWinHandle = driver.getWindowHandle();
//Click the button or link which populates the window
driver.findElement(By.id(actionBtn)).click();
Thread.sleep(5000);
Set<?> popupHandles = driver.getWindowHandles();
//SOP *popupHandles*
Iterator<?> iterator = popupHandles.iterator();
while(iterator.hasNext())
{
String popupHandle = iterator.next().toString();
if(!popupHandle.contains(parentWinHandle)) {
driver.switchTo().window(popupHandle);
Thread.sleep(3000);
//Perform the operation you want to do
driver.switchTo().window(parentWinHandle);
}
}
Now pass the array index value to perform the close operation.