Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

selenium
webdriver
communitycreator

What is close() and quit() in Selenium Webdriver?

Mohammad Razi ul Haq

In Selenium Webdriver, there are two methods to close a browser window, close() and quit(). These methods are often used interchangeably, but they have different functions.

close()

The close() method is a Webdriver command that closes the browser window currently in focus. It is best to use the close() command when multiple browser tabs or windows are open. If only one window is open in the entire browser, then the close()command will quit the entire browser session.

quit()

The quit() command quits the entire browser session with all its tabs and windows. The command is used when the user wants to end the program. If you do not call quit() at the end of the program, the WebDriver session will not close properly and may lead to memory leaks as files will not be wiped off memory.

Code

public void TestFunction() throws Exception {

      WebDriver driver = new ChromeDriver();
      driver.get("https://www.educative.io");
      String current_window = driver.getWindowHandle();
      Set<String> all_Windows = driver.getWindowHandles();
      Iterator<String> i = all_Windows.iterator();
      while(i.hasNext()){
         String child_window = i.next();
         if(!child_window.equalsIgnoreCase(current_Window)){
            driver.switchTo().window(child_window);
            System.out.println("The current window is "+child_window);
            // close() method closes the child window in focus, the parent window is still open
            driver.close()
         } else {
            System.out.println("No other window open");
         }
      }
      // quit() will close all the webdriver instances, so parent window will close      
      driver.quit();
   }
}

RELATED TAGS

selenium
webdriver
communitycreator

CONTRIBUTOR

Mohammad Razi ul Haq
RELATED COURSES

View all Courses

Keep Exploring