The quit() method is a fundamental feature of Selenium WebDriver in Java, designed for the full termination of browser sessions started during automated testing. Proper use of this method ensures that your browser automation scripts end cleanly and all resources are freed, preventing memory leaks and unwanted background processes.
What Does quit() Do?
- Closes All Browser Windows/Tabs: Invoking
quit()
shuts down every browser window or tab opened by the current WebDriver session. - Ends the WebDriver Session: The method terminates the WebDriver instance, effectively ending the session and releasing the associated resources.
- Cleanup: Suitable for final cleanup at the end of test execution, ensuring no browsers are left running unintentionally.
Syntax
driver.quit();
driver
references your active WebDriver instance (such asChromeDriver
,FirefoxDriver
, etc.).
Complete Code Example
Here’s a basic example demonstrating how to use quit()
in a simple Selenium WebDriver script:
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class QuitExample { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get("https://www.example.com"); // Terminate the browser session and close all windows/tabs driver.quit(); } }
In this example, quit() ensures the session ends cleanly regardless of how many windows or tabs were opened during execution.
quit() vs. close() Methods: Key Differences
Feature | close() | quit() |
---|---|---|
Closes current window/tab only | Yes | Yes (if last window) |
Closes all browser windows/tabs | No | Yes |
Ends WebDriver session | No (unless last window) | Yes |
Typical use | Close popups or specific windows/tabs | End of script/test, full cleanup |
close()
shuts just the currently focused window/tab; session persists if others are open.quit()
closes all and terminates the entire driver session.
Best Practices
- Always use
quit()
at the end of your automation scripts or test suites to release browser and driver resources. - If an exception occurs during execution, ensure
quit()
is still called (use try-finally or appropriate test teardown methods). - Avoid using the driver after calling
quit()
; it is no longer valid and will throw exceptions on subsequent calls.
When to Use quit() Method?
- Final step in any test script to guarantee no browsers remain open.
- During test suite teardown to prevent lingering sessions that could interfere with later tests.
- In resource-constrained environments, where cleanup is crucial for repeated test executions.
Key Points
- Comprehensive cleanup: Ensures no browser windows/tabs or driver instances remain.
- Prevents resource leaks: Essential for robust, maintainable test automation frameworks.
- One call is enough: No need to call
close()
individually beforequit()
;quit()
handles everything.