ScreenshotNeo

BlogHow-to

How to Close a Browser Tab in Selenium

Close the selected Selenium tab with `close()`, then switch to a remaining window handle before continuing. Learn the Python, Java, JavaScript, and C# patterns, recovery steps, and when to use `quit()`.

By the ScreenshotNeo team4 October 20267 min read

To close one browser tab in Selenium, switch WebDriver to that tab and call the binding’s close() method. If the session should continue, switch to a different window handle that is still open before issuing more page commands. Use quit() when you want to end the entire WebDriver session and close all its tabs and windows.

This distinction matters because close() closes the currently selected tab or window; it does not automatically select another one. Selenium documents that continuing to use the closed context can raise a No Such Window Exception. See Selenium’s official guide to working with windows and tabs.

Python: close a tab and return to the original tab

Save the handle of the tab you want to keep, switch to the tab you want to close, close it, then switch back. This complete example opens a second tab, visits a page, closes the second tab, and resumes on the original tab.

from selenium import webdriver

 driver = webdriver.Chrome()
 try:
     driver.get("https://example.com")
     original_handle = driver.current_window_handle

     driver.switch_to.new_window("tab")
     driver.get("https://example.org")
     tab_to_close = driver.current_window_handle

     driver.close()  # Closes the currently selected tab.
     driver.switch_to.window(original_handle)

     print(driver.title)  # Commands now target the original tab.
 finally:
     driver.quit()  # End the whole session when finished.

Remove the extra leading space before driver in the first line inside try if copying this snippet into an environment that rejects indentation as shown; the intended indentation is one level inside the try block. Install Selenium with python -m pip install selenium. The example uses Selenium 4’s switch_to.new_window("tab") API.

Close a tab that is already open

Keep the handle you intend to return to, identify the target tab’s handle, and switch explicitly. Do not assume the first or last handle is a particular tab; use handles as identifiers and track them when you create tabs.

keep_handle = driver.current_window_handle
handles_before = set(driver.window_handles)

# Perform the action that opens another tab, then wait until it appears.
# For example, click a link that opens a new tab.

new_handles = set(driver.window_handles) - handles_before
if len(new_handles) != 1:
    raise RuntimeError(f"Expected one new tab, found {len(new_handles)}")

target_handle = new_handles.pop()
driver.switch_to.window(target_handle)
driver.close()
driver.switch_to.window(keep_handle)

In real automation, wait for the new handle to appear instead of reading window_handles immediately after an action that opens a tab. If multiple tabs may open, identify the target by page title, URL, or another page-specific condition, then close only after confirming the selected handle.

Java, JavaScript, and C# equivalents

Java

String original = driver.getWindowHandle();

// Switch to the tab you intend to close, if needed.
driver.switchTo().window(tabToCloseHandle);
driver.close();
driver.switchTo().window(original);

Use this inside a Selenium 4 Java project with a configured WebDriver. Ensure original still identifies an open tab before switching back.

JavaScript (Node.js)

const original = await driver.getWindowHandle();

// Switch to the tab you intend to close, if needed.
await driver.switchTo().window(tabToCloseHandle);
await driver.close();
await driver.switchTo().window(original);

The JavaScript Selenium WebDriver API is asynchronous, so await each operation. The tabToCloseHandle value must be a valid handle returned by the driver.

C#

string original = driver.CurrentWindowHandle;

// Switch to the tab you intend to close, if needed.
driver.SwitchTo().Window(tabToCloseHandle);
driver.Close();
driver.SwitchTo().Window(original);

The method names vary by language binding, but the sequence is the same: select the target context, close it, and select a surviving handle.

What close() does—and what it does not do

Operation Effect Use it when
close() Closes the currently selected tab or window. You want to remove one context and keep the session running.
Switch to a handle Selects a currently open tab or window for subsequent WebDriver commands. You need to continue after closing a tab, or direct work to a different tab.
quit() Ends the WebDriver session and closes its associated windows and processes. The browser automation is finished.

Closing the last remaining tab can leave no usable browsing context for the next command. If the session is over, call quit() as cleanup. If you intend to keep working, leave at least one tab open and switch to its handle.

Wait for a tab before switching or closing it

When a click opens a tab, WebDriver may return before the new context is available. A wait avoids racing the browser. This Python helper waits for a handle not present in the original set:

from selenium.webdriver.support.ui import WebDriverWait

before = set(driver.window_handles)
# Click the control that opens a new tab here.
new_handle = WebDriverWait(driver, 10).until(
    lambda d: next(iter(set(d.window_handles) - before), False)
)
driver.switch_to.window(new_handle)
# Inspect the page or close it once you have confirmed it is the target.

If your click can open more than one tab, wait for the expected count or inspect each newly observed handle and match the intended page. A timeout should be treated as a failed tab-opening step, not as a reason to close an arbitrary existing tab.

Common errors and fixes

Symptom Likely cause Fix
NoSuchWindowException or “no such window” A command ran while WebDriver was still associated with a tab that had been closed, or the chosen handle is no longer open. Switch to a handle currently present in driver.window_handles. Check that the saved return handle was not closed too.
“No window found” after closing The closed tab was the last available context, or another part of the test closed the remaining tab. End the session with quit(), or change the flow so a tab to continue in remains open.
The wrong tab closes The driver was not switched to the intended tab, or code relied on handle ordering. Track handles when opening tabs, compare before and after sets, and verify the target page before calling close().
New tab is missing intermittently The script checked handles before the browser finished opening the tab. Wait for the handle count or a new handle, then switch. Give the wait a bounded timeout and report a useful failure if it expires.
Later test cases inherit stray tabs or a browser Session cleanup was skipped after a failure. Put driver.quit() in a finally block or the test framework’s teardown hook.

Reliability and performance notes

  • Store the return handle: Save it before switching away. This is more reliable than guessing which handle is the original tab later.
  • Wait for asynchronous changes: Tab creation and navigation are asynchronous. Wait for a handle or page condition before acting on the new tab.
  • Keep cleanup unconditional: Use teardown or finally to call quit(), including when assertions or navigation fail.
  • Do not confuse closing with selecting: Call switch_to.window(handle) (or the binding equivalent) after a close if the test continues.
  • Keep the scope small: Close only the context the test owns. A handle can become stale if the page or another actor closes its tab.

Closing a tab is a local browser-control operation; there is no need to capture a screenshot to perform it. If a test also needs visual evidence, capture the desired page before closing its tab.

Or skip the browser setup

If your goal is to save a page image rather than automate a browser tab, ScreenshotNeo is a website screenshot API and MCP server. A single GET request captures a URL as PNG, JPEG, WebP, or PDF. See the ScreenshotNeo API documentation for parameters and response details.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const image = Buffer.from(await res.arrayBuffer());
await (await import('node:fs/promises')).writeFile('shot.webp', image);
  • Cookie and consent banners, newsletter popups, and chat widgets are removed before the shot; each cleanup step can be turned off.
  • Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed. Response headers report the page verdict and billing status.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients.
  • The free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 screenshots; every feature is on every plan.

Create a free ScreenshotNeo account for 1,000 screenshots a month with no card.

FAQ

Does close() close every tab?

No. It closes the currently selected tab or window. Use quit() to end the session and close all associated windows.

Do I need Selenium 4 to close a tab?

The close-and-switch workflow applies across bindings. Selenium’s documented new-window API, used in the Python example to open a tab, is available in Selenium 4 and later.

Can I continue using the same WebDriver after closing a tab?

Yes, if another window remains open and you switch to its valid handle before sending more page commands.

Should I use close() or quit() in test teardown?

Use quit() when the test’s browser session is finished. Use close() during a test when you are deliberately removing one tab while keeping the session alive.