This is a code I use when I need to work with a following pop-up window, close it and go back to my main window. Of course, it has been simplified for the purpose of this answer. It maintains a handle of the original window (main) so it can make a difference between the others.
It requires an explicit WebDriverWait because I did have problems during development that code got to run before the window actually got open, so this might not be an ideal condition,
function manipulatePopUp(final WebDriver driver, final WebDriverWait wait) {
final String mainWindowHandle = driver.getWindowHandle();
driver.findElement(By.id("linkThatOpensPopUp")).click();
wait.until(new ExpectedConditions<Boolean>() {
@Override
public Boolean apply(WebDriver d) {
return (d.getWindowHandles().size() != 1);
}
});
for (String activeHandle : driver.getWindowHandles()) {
if (!activeHandle.equals(mainWindowHandle)) {
driver.switchTo().window(activeHandle);
}
}
driver.close();
driver.switchTo().window(mainWindowHandle);
}