After a tab opens, Selenium may still be attached to the original tab. Save the original window handle, wait for the new handle, switch to it explicitly, wait for the destination page to become ready, and only then read driver.current_url. A visible tab change in Chrome is not the same as a WebDriver context switch. Headless mode can expose timing or version differences, but the first diagnosis is always the active handle and page readiness.
The reliable fix: handle, switch, wait, then read the URL
Selenium addresses both browser windows and tabs through window handles; WebDriver does not distinguish between them. The tab that appears visually focused is not necessarily Selenium’s current browsing context. If you read the URL before switching, you can receive the parent page’s URL, an intermediate URL, or an exception after the target has closed.
- Store
driver.current_window_handlebefore the click or script that opens the tab. - Wait until the number of window handles reaches the number you expect.
- Find the handle that is not the saved original and call
driver.switch_to.window(). - Wait for a destination condition, such as a title, element, or application-specific ready state.
- Read
driver.current_urlwhile that handle is still open.
Do not assume that the new tab is always at index 1. A test suite may already have several tabs, and handle ordering is not a stable way to identify a destination.
A complete Python example
This example opens a link that creates a new tab, switches to the newly created handle, waits for a known heading, and then retrieves the URL.
#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.add_argument("--headless=new")
options.add_argument("--window-size=1440,1000")
driver = webdriver.Chrome(options=options)
wait = WebDriverWait(driver, 30)
try:
driver.get("https://example.test/source")
original = driver.current_window_handle
before = set(driver.window_handles)
driver.find_element(By.CSS_SELECTOR, "a[target='_blank']").click()
# Wait for a handle that was not present before the click.
wait.until(lambda d: len(set(d.window_handles) - before) == 1)
new_handles = set(driver.window_handles) - before
new_handle = new_handles.pop()
driver.switch_to.window(new_handle)
# Replace this selector with a reliable element on the destination page.
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "h1")))
destination_url = driver.current_url
print(destination_url)
finally:
# Quit closes every remaining tab and the driver process.
driver.quit()
If the application can open more than one tab, wait for the expected count and inspect every handle instead of assuming one new handle. You can identify a tab by switching to it and checking its title or a distinctive element, then continue with the matching handle.
Waiting correctly in headless Chrome
Wait for the handle, not a fixed sleep
time.sleep(2) can appear to fix the problem on a fast machine and fail under load. An explicit wait polls until the browser reports the required state and returns as soon as it is available. Use a window-count or set-difference condition for the new tab.
wait.until(lambda d: len(d.window_handles) == 2)
new_handle = next(h for h in driver.window_handles if h != original)
driver.switch_to.window(new_handle)
Use the set-difference form when other tabs may exist:
old_handles = set(driver.window_handles)
# trigger the action here
wait.until(lambda d: set(d.window_handles) - old_handles)
new_handle = next(iter(set(driver.window_handles) - old_handles))
Wait for a page condition before reading the URL
A handle can exist while navigation is still in progress. Wait for a title, a stable element, or a condition your application controls. A title wait is useful when the destination has a predictable title:
Rank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
wait.until(EC.title_contains("Checkout"))
print(driver.current_url)
An element wait is usually stronger because it confirms that meaningful page content has loaded:
wait.until(EC.visibility_of_element_located((By.ID, "checkout-summary")))
url = driver.current_url
For single-page applications, the URL may change through client-side routing after the first document loads. Wait for the route-specific element or URL pattern rather than reading immediately after the tab appears.
Handling tabs that close or redirect
Switch back when the target closes
A closed tab is no longer a valid browsing context. Continuing to use it can raise NoSuchWindowException. Keep the original handle and verify that it remains in driver.window_handles before switching back.
if new_handle not in driver.window_handles:
if original in driver.window_handles:
driver.switch_to.window(original)
print("The destination tab closed before its URL was read")
else:
raise RuntimeError("Neither the destination nor the original tab is open")
Capture the URL before closing
If your workflow closes the child tab, read and store its URL first, then switch to the parent and close the child deliberately.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsRank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
driver.switch_to.window(new_handle)
wait.until(EC.presence_of_element_located((By.TAG_NAME, "body")))
child_url = driver.current_url
driver.close()
driver.switch_to.window(original)
Do not call driver.close() on the only remaining tab unless you intend to end the session. Use driver.quit() for final cleanup.
Equivalent URL calls in Java and JavaScript
The context rule is the same in every Selenium binding: switch first, then retrieve the current URL from that context.
Java
String original = driver.getWindowHandle();
Set<String> before = driver.getWindowHandles();
// trigger the action that opens the tab
new WebDriverWait(driver, Duration.ofSeconds(30))
.until(d -> d.getWindowHandles().size() > before.size());
for (String handle : driver.getWindowHandles()) {
if (!before.contains(handle)) {
driver.switchTo().window(handle);
break;
}
}
new WebDriverWait(driver, Duration.ofSeconds(30))
.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("h1")));
String url = driver.getCurrentUrl();
JavaScript (Node.js Selenium WebDriver)
const original = await driver.getWindowHandle();
const before = new Set(await driver.getAllWindowHandles());
// trigger the action that opens the tab
await driver.wait(async () => {
const handles = await driver.getAllWindowHandles();
return handles.length > before.size;
}, 30000);
const handles = await driver.getAllWindowHandles();
const newHandle = handles.find(h => !before.has(h));
await driver.switchTo().window(newHandle);
await driver.wait(async () => (await driver.getTitle()).includes('Checkout'), 30000);
const url = await driver.getCurrentUrl();
Headless Chrome options and version differences
Chrome’s headless implementation has changed. Older headless Chrome was a separate implementation with different bugs and feature behavior; newer Chrome provides a mode intended to share the regular Chrome implementation. The --headless=new option was documented around Chrome 112, but available flags and defaults depend on the Chrome version installed on the machine. Treat that flag as a version-sensitive setting, not a universal repair.
Run the same test headful and headless. If headful succeeds and headless fails, record the exact Chrome version, ChromeDriver version, Selenium binding version, operating system, and headless arguments. That comparison narrows the cause; it does not prove that headless itself is responsible. Keep Chrome and ChromeDriver compatible and avoid mixing a system driver with a different browser installation.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Diagnostics that expose the wrong context
Add temporary logging immediately before and after every switch:
print("current:", driver.current_window_handle)
print("handles:", driver.window_handles)
print("title:", driver.title)
print("url:", driver.current_url)
- Current handle is the original: the switch did not happen, or it happened before the new handle appeared.
- Handle list never grows: the click may be blocked, a popup may be suppressed, or the application opened a same-tab navigation instead.
- Handle appears but the URL is about:blank: navigation has not completed, or the new tab requires a user gesture or script to continue.
- The title or element wait times out: the destination may have redirected, failed to load, required authentication, or used a different selector in headless mode.
NoSuchWindowExceptionappears: the target closed or the session lost that context; select a handle still present indriver.window_handles.
Log whether the action opened a new tab or closed one. Also record the handle list before the action, after the action, after switching, and immediately before URL retrieval.
Common failures and precise fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| URL is the parent page | WebDriver remained on the original handle | Save the original, wait for the new handle, call switch_to.window(new_handle), then read the URL. |
| Intermittent empty or old URL | URL read during navigation | Wait for a destination title, element, or route-specific condition. |
| Works with two tabs, fails with three | Code assumes index 1 is the target | Use set differences and identify the handle by title or content. |
NoSuchWindowException |
Target was closed or context became invalid | Check live handles and switch to a saved handle that remains open. |
| Headless only failure | Timing, rendering, browser flags, or version difference | Compare headful/headless runs and record Selenium, Chrome, driver, OS, and flags; then fix the first differing condition. |
| Wait never finds a new handle | Action navigated the same tab or was not triggered | Verify the click target, popup behavior, overlays, and whether the application uses same-tab navigation. |
Reliability and performance practices
- Create one explicit wait with a timeout appropriate for your environment rather than scattering arbitrary sleeps.
- Use stable selectors and destination-specific readiness checks. A generic
bodywait confirms very little. - Keep the original handle in a variable and avoid relying on handle ordering.
- Close child tabs when finished, but always switch to a live handle before continuing.
- Capture diagnostic data only when a test fails to keep normal runs fast: versions, flags, handles, title, URL, and page-source or screenshot artifacts where permitted.
- Run repeated headless tests if the failure is intermittent; a single successful run does not establish that timing is fixed.
There is no evidence that headless mode universally causes stale or incorrect URLs. The dependable correction is explicit context management plus a wait for the destination state.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Or skip the browser setup
If your actual goal is a clean image or PDF of a URL rather than Selenium interaction, ScreenshotNeo provides a single HTTP request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response identifies the result with X-Page-Verdict and X-Billed headers. It also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
Free tools Windows power users keep installed
One-click scans. No signup required.
See the ScreenshotNeo website and API documentation for parameter details.
Best Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python
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)
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo supports PNG, JPEG, WebP, and PDF output plus full-page capture, lazy-image loading, CSS-selector element capture, device presets, custom viewports, retina scale, PDF paper and page options, custom CSS and JavaScript, clicks, selector or network-idle waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, chosen-TTL caching, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, usage reporting, and an OpenAPI specification. Its parameter names are compatible with those used by many screenshot APIs, which can simplify migration.
| Plan | Included shots | Price |
|---|---|---|
| Free | 1,000 per month | $0, no card |
| Starter | 3,000 | $5 |
| Growth | 15,000 | $15 |
| Pro | 60,000 | $39 |
| Scale | 250,000 | $99 |
| Business | 1,000,000 | $249 |
Yearly billing gives two months free, and every feature is available on every plan. Create a free ScreenshotNeo account to get 1,000 screenshots each month without adding a card; paid plans start at $5 for 3,000 shots.
Frequently Asked Questions
What does Selenium return for the current URL?
Python uses driver.current_url; Java uses driver.getCurrentUrl(); the JavaScript Selenium binding uses driver.getCurrentUrl(). Each returns the URL for the currently selected WebDriver window context.
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Can I identify a tab by its window handle across test runs?
No. Handles identify contexts within one WebDriver session and should be treated as opaque values. Save and compare them during that session instead of persisting them.
Should I use an implicit wait for tab switching?
An explicit wait for the handle count and destination condition makes this workflow clearer and more targeted. An implicit wait does not replace the explicit window-context switch.
Why might a new tab contain a different final URL than the link target?
The destination can redirect, authenticate, or update its route with client-side code. Read the URL only after a condition that represents the final page state.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Recommended Free Tools

