</>

Technology

Selenium

Difficulty

Beginner

Interview Question

What is the difference between driver.close() and driver.quit() in Selenium?

Answer

driver.close() vs driver.quit()

This is a very commonly asked interview question. The difference is critical in multi-window tests.

driver.close()

  • Closes only the currently focused browser window/tab
  • The WebDriver session remains alive
  • Other open windows stay open
  • Must switch to another window after closing to continue
Java
String mainWindow = driver.getWindowHandle();

// Open a new tab
driver.switchTo().newWindow(WindowType.TAB);
driver.get("https://google.com");

// Close only this tab
driver.close();

// Switch back to main window — session still active
driver.switchTo().window(mainWindow);
driver.findElement(By.id("element")).click(); // still works

driver.quit()

  • Closes ALL browser windows opened by this WebDriver session
  • Ends the WebDriver session completely
  • Kills the browser driver process (chromedriver.exe, geckodriver.exe)
  • Releases all resources — no memory leak
Java
// Close all windows and end session
driver.quit();

// After quit(), driver is null — any call throws exception
// driver.findElement(...) → SessionNotCreatedException

Comparison Table

Aspectdriver.close()driver.quit()
Windows closedCurrent window onlyAll windows
WebDriver sessionStill aliveTerminated
Driver processStill runningKilled
MemoryPartial releaseFull release
After callCan continue on other windowCannot use driver

Common Mistake — Memory Leak

Java
// BAD — close() leaves driver process running if only one window
@AfterMethod
public void tearDown() {
    driver.close(); // WRONG — chromedriver.exe still running!
}

// CORRECT — always quit() in teardown
@AfterMethod(alwaysRun = true)
public void tearDown() {
    if (driver != null) {
        driver.quit(); // closes all + kills chromedriver.exe
    }
}

When to Use close()

Java
// Multi-window test: open popup, verify, close it, return to main
String main = driver.getWindowHandle();
driver.findElement(By.linkText("Open Terms")).click();

// Wait for new window
new WebDriverWait(driver, Duration.ofSeconds(5))
    .until(ExpectedConditions.numberOfWindowsToBe(2));

// Work in popup
driver.getWindowHandles().stream()
    .filter(h -> !h.equals(main))
    .forEach(h -> driver.switchTo().window(h));

// Verify content, then close popup
Assert.assertTrue(driver.getTitle().contains("Terms"));
driver.close(); // close just the popup

// Switch back to main
driver.switchTo().window(main);

Rule of thumb: Use close() during test execution to close popup windows. Use quit() in @AfterMethod/@AfterTest to clean up.

Follow AutomateQA

Related Topics