Difference Between close() and quit() Methods

close() : Closes the current browser or a page which is currently having the focus.

quit() : It is used to destroy the web driver instance. Means it will close all browsers associated with driver session.

So, If there is only one window is opened by your script then close() and quit() methods will technically do the same.

Below is the small program that would help to understand these methods. This program will gonna open a Google page, search for ‘Sign In’ link and will open ‘Sign In’ page in a window and then closes the parent browser, leaving the new browser opened because we are using close() command in following script to close the browser.

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;

public class SampleScript {

     public static void main(String s[]) throws InterruptedException {
          //Initialize driver instance
         WebDriver driver=new FirefoxDriver();

         //Launch Google page
         driver.get("http://www.google.com/");
        
         //Search for 'Sign In' link and store it in a variable
         WebElement signInElement = driver.findElement(By.linkText("Sign in"));
         
         //Perform Right click on 'sign In' link and open page in a new window
         Actions action = new Actions(driver);
         action.moveToElement(signInElement);
         action.contextClick(signInElement).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
         
         Thread.sleep(3000);
         driver.close();

     }
}

In above program, if you use driver.quit() command, it will close all browsers associated with driver session.

If you really like the information provided above, please don’t forget to like us on Facebook, you can also leave the comment.

Leave a Reply

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