The close() method is an essential part of Selenium WebDriver’s API in Java, specifically designed for closing the current browser window or tab that is in focus during test automation. Mastery of this method helps manage browser sessions reliably, especially when dealing with multiple windows or tabs.
What Does close() Do?
- Closes the Current Window in Focus: When invoked,
close()
shuts only the browser window or tab currently controlled by WebDriver. - Session Remains Active: If multiple windows exist, the WebDriver session continues for remaining open windows or tabs.
- Single Window Behavior: If
close()
is called on the final open window or tab, it effectively ends the browser session, similar to thequit()
method.
Syntax
driver.close();
- Here,
driver
refers to your active WebDriver instance.
Complete Code Example
import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class CloseExample { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver"); WebDriver driver = new ChromeDriver(); driver.get("https://www.example.com"); // Close the current browser window driver.close(); } }
Result: Only the browser window currently controlled by WebDriver closes. The WebDriver session persists if other windows remain open.
Working with Multiple Windows
When automating interactions across multiple windows or tabs, close()
is used after switching WebDriver’s control to the intended window using switchTo().window(windowHandle)
:
// Switch to a specific window first
driver.switchTo().window(windowHandle);
driver.close(); // Closes the focused window only
This allows precise control over which window gets closed, leaving others unaffected.
close() vs quit() Methods: Key Differences
Feature | close() | quit() |
---|---|---|
Closes current window/tab only | Yes | No, closes all windows/tabs |
Closes all browser windows/tabs | No | Yes |
Ends WebDriver session | No (unless last window is closed) | Yes |
Common use | Close popups, child windows | End of test suite or script |
Typical Use Cases
- Closing popups or child windows while retaining the main browser session.
- Sequentially closing test-created windows without terminating the entire browser session.
- Cleaning up after specific interactions in a multi-window flow.
Best Practices
- Switch to the correct window before calling
close()
to avoid unintentional closure. - Use
quit()
for complete cleanup at the end of your test suite, as it releases all browser resources. - Be aware that calling
close()
on the last open window will terminate the WebDriver session.