We close browsers in tests to free up resources and avoid leftover windows. Knowing the difference between close() and quit() helps control browser behavior properly.
0
0
Closing browser (close vs quit) in Selenium Java
Introduction
When you want to close only the current browser tab or window.
When you want to end the entire browser session and close all windows.
When cleaning up after a test to avoid leftover browser processes.
When running multiple tests and you want to keep the browser open between tests.
When debugging and you want to close just one window but keep others open.
Syntax
Selenium Java
driver.close(); driver.quit();
close() closes the current browser window or tab.
quit() closes all browser windows and ends the WebDriver session.
Examples
This closes only the current browser window or tab that the WebDriver is controlling.
Selenium Java
driver.close();
This closes all browser windows opened by the WebDriver and ends the session.
Selenium Java
driver.quit();
Opens a page and then closes the current window only.
Selenium Java
driver.get("https://example.com");
driver.close();Opens a page and then closes all windows and ends the session.
Selenium Java
driver.get("https://example.com");
driver.quit();Sample Program
This program shows the difference between close() and quit(). After close(), the driver session still exists but the current window is closed. After quit(), the driver session ends and cannot be used.
Selenium Java
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class BrowserCloseVsQuit { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get("https://example.com"); System.out.println("Title before close: " + driver.getTitle()); driver.close(); try { driver.getTitle(); } catch (Exception e) { System.out.println("After close(), driver session is still alive but current window is closed."); } // Start new driver for quit demo driver = new ChromeDriver(); driver.get("https://example.com"); System.out.println("Title before quit: " + driver.getTitle()); driver.quit(); try { driver.getTitle(); } catch (Exception e) { System.out.println("After quit(), driver session is closed and unusable."); } } }
OutputSuccess
Important Notes
Use close() when you want to close one window but keep the session alive.
Use quit() to end the session and close all windows to free resources.
Calling close() on the last window may also end the session depending on the browser.
Summary
close() closes the current browser window or tab.
quit() closes all browser windows and ends the WebDriver session.
Choose the method based on whether you want to keep the session alive or end it completely.