Closing browser (close vs quit) in Selenium Java - Automation Approaches Compared
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.NoSuchSessionException; public class BrowserCloseVsQuitTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); // Test driver.close() WebDriver driver = new ChromeDriver(); try { driver.get("https://example.com"); // Close current window driver.close(); // After close(), try to get current URL to check if session is alive try { String url = driver.getCurrentUrl(); System.out.println("Session alive after close(), current URL: " + url); } catch (NoSuchSessionException e) { System.out.println("Session ended after close(): " + e.getMessage()); } } catch (Exception e) { e.printStackTrace(); } finally { // Quit driver to clean up if session still alive try { driver.quit(); } catch (Exception ignored) {} } // Test driver.quit() WebDriver driver2 = new ChromeDriver(); try { driver2.get("https://example.com"); // Quit closes all windows and ends session driver2.quit(); // After quit(), try to get current URL to verify session ended try { String url = driver2.getCurrentUrl(); System.out.println("Session alive after quit(), current URL: " + url); } catch (NoSuchSessionException e) { System.out.println("Session ended after quit(): " + e.getMessage()); } } catch (Exception e) { e.printStackTrace(); } } }
This code demonstrates the difference between driver.close() and driver.quit() in Selenium WebDriver using Java.
First, it opens a browser and navigates to example.com, then calls driver.close() which closes the current browser window. We then try to get the current URL to check if the WebDriver session is still alive. Usually, if only one window was open, the session may still be alive but the window is closed.
Next, it opens a new browser session and navigates to example.com again, then calls driver.quit() which closes all browser windows and ends the WebDriver session. Trying to get the current URL after quit throws a NoSuchSessionException, confirming the session ended.
Using try-finally blocks ensures the driver quits properly to avoid leftover browser processes. Catching exceptions helps verify session state after close and quit.
Now add data-driven testing to open multiple URLs and test close vs quit behavior for each.