To check how many windows are open in the current set we create a set and check its size
Set windows_open = driver.getWindowHandles();
Then if two windows are open we iterate through those windows and go to the pop window and close it and then switch back to the main window.
Iterator<String> it = windows_open.iterator();
if(windows_open.size()==2){
String main_window = it.next();
String popUp_window = it.next();
driver.switchTo.window(popUp_window);
driver.close();
driver.switchTo.window(main_window);}
}
In IE we need to type the below command before switching to the popup windows
driver.switchTo().activeElement();