The below explanation should explain the difference between driver.close and driver.quit methods in WebDriver. I hope you find it useful.
driver.close and driver.quit are two different methods for closing the browser session in Selenium WebDriver.
Understanding both of them and knowing when to use each method is important in your test execution. Therefore, I have tried to shed some light on both of these methods.
driver.close - This method closes the browser window on which the focus is set. driver.quit close the session of webdriver while
driver.close only close the current window on which selenium control is present but webdriver session not close yet, if no other window open and you call
driver.close then it also close the session of webdriver.
driver.quit – This method basically calls driver.dispose a now internal method which in turn closes all of the browser windows and
ends the WebDriver session gracefully.
driver.dispose - As mentioned previously, is an internal method of WebDriver which has been silently dropped according to another answer - Verification needed. This method really doesn't have a use-case in a normal test workflow as either of the previous methods should work for most use cases.
Explanation use case: You should use driver.quit whenever you want to end the program. It will close all opened browser windows and terminates the WebDriver session. If you do not use driver.quit at the end of the program, the WebDriver session will not close properly and files would not be cleared from memory. This may result in memory leak errors.
............
Now In that case you need to specific browser.
Below is code which will close all the child windows except the Main window.
String homeWindow = driver.getWindowHandle();
Set<String> allWindows = driver.getWindowHandles();
//Use Iterator to iterate over windows
Iterator<String> windowIterator = allWindows.iterator();
//Verify next window is available
while(windowIterator.hasNext())
{
//Store the Recruiter window id
String childWindow = windowIterator.next();
}
//Here we will compare if parent window is not equal to child window
if (homeWindow.equals(childWindow))
{
driver.switchTo().window(childWindow);
driver.close();
}
Now here you need to modify or add the condition according to your need
if (homeWindow.equals(childWindow))
{
driver.switchTo().window(childWindow);
driver.close();
}
Currently it is checking only if home window is equal to childwindow or not. Here you need to specify the condition like which id's you want to close. I never tried it so just suggested you the way to achive your requirement.