The close() vs. quit() Method in Selenium

Not sure about the difference between the close() and the quit() method in Selenium WebDriver? Here’s what you need to know.

Published Categorized as Web & Code

If you’re new to browser automation with Selenium WebDriver, you might be wondering about the difference between the driver.close() and driver.quit() methods.

At first glance, these two methods seem very alike. But they’re really not, and understanding the difference between them will help you prevent memory leaks and prevent your testing sessions from ending prematurely.

Here’s the long story short:

Both the close() and the quit() methods are ways to close the browser in Selenium. However, the quit() method quits the driver and closes all browser windows associated with that session, whereas the close() method closes just the current browser window and only quits the driver if no other windows are left.

It’s important to note that this only makes a difference if you’re opening multiple browser windows in your test session. If the entire test session takes place in a single browser window, then the close() and quit() methods will result in one and the same outcome — closing the window and terminating the driver.

The close() Method

// Close the browser window in focus

In Selenium WebDriver, the close() method closes the browser window in focus. If there are other browser windows within the testing session, they will stay open. Else, the driver instance will be terminated.

Use the close() method to get rid of any browser windows you no longer need in your testing session. This will prevent memory leaks.

The quit() Method

// Close all browser windows and quit driver

In Selenium WebDriver, the quit() method quits all open browser windows within the testing session and terminates the driver instance.

Don’t use the quit() method in the middle of a testing session unless you plan to open a new driver instance immediately after (and re-open any URLs you will need), or your testing session will end prematurely.

In Summary

To sum things up, the difference between the close() and quit() methods in Selenium is in the extent to which you’d like to terminate the testing session. The former comes in handy for closing pop-up windows or temporary tabs, and the latter for ending the session when the test case is completed and you no longer need the driver instance.

By Dim Nikov

Editor of Maker's Aid. Part programmer, part marketer. Making things on the web and helping others do the same since the 2000s. Yes, I had Friendster and Myspace.

Leave a comment

Your email address will not be published. Required fields are marked *