DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
Redmond desk5 min

How to Handle Multiple Windows in Selenium WebDriver with Java

Save the original Selenium window handle, wait for a new one, switch to it, and return safely after closing a popup or tab.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To handle a popup or new tab in Selenium WebDriver with Java, save the current window handle, trigger the action, wait for a new handle, switch to it, and then switch back to the saved handle when you are done. WebDriver does not automatically follow the browser’s visible focus. Tabs and windows use the same handle-based workflow.

How do window handles work in Selenium?

A window handle is an identifier for a browser browsing context. Use driver.getWindowHandle() to get the handle for the selected context, and driver.getWindowHandles() to retrieve the handles for all open contexts. Select one with driver.switchTo().window(handle).

A browser may visibly focus a tab or window opened by a click, but WebDriver commands remain scoped to the context it has selected. Switch explicitly before reading a title, finding an element, or interacting with the new page.

How do I switch to a new window in Selenium WebDriver using Java?

Save the original set of handles before the action, wait until an additional handle appears, and find the handle that was not in the original set. Comparing sets avoids relying on an assumed handle order and also works when the test starts with more than one open context.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
LAPGEAR Home Office Pro Lap Desk - Black Carbon, Fits 15.6” Laptops
  • Spacious Design: Measuring 21.1" wide and 14.1" deep, our lap desk comfortably fits most laptops up to 15.6". Extra room for accessories ensures convenience.
  • Enhanced Functionality: Packed with handy features, including a 5x9" precision tracking mouse pad and a built-in phone slot for seamless work or video calls. Plus, enjoy ergonomic support with the integrated cushioned wrist rest.
  • Cool Comfort: Enjoy a stable surface with our lap desk's dual bolster cushion, designed for comfort and airflow, keeping your lap cool during extended use.
  • Durable Surface: Work with confidence on our lap desk's solid surface, featuring a sleek black carbon color, ensuring optimal air circulation to prevent your laptop from overheating.
  • On-the-Go Convenience: With an integrated handle and lightweight design (2.8 lbs), our lap desk is portable for travel or moving around the house, offering flexibility in any space.
import java.time.Duration;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchWindowException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

String originalHandle = driver.getWindowHandle();
Set<String> handlesBefore = driver.getWindowHandles();

// Trigger the action that opens a new tab or window.
driver.findElement(By.linkText("Open new window")).click();

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(d -> d.getWindowHandles().size() > handlesBefore.size());

String newHandle = driver.getWindowHandles().stream()
    .filter(handle -> !handlesBefore.contains(handle))
    .findFirst()
    .orElseThrow(() -> new NoSuchWindowException("New window did not appear"));

driver.switchTo().window(newHandle);
wait.until(d -> !d.getTitle().isEmpty());

// Assert the expected title or page content here.

// When finished, close this child context and return to the parent.
driver.close();
driver.switchTo().window(originalHandle);

The example uses a ten-second explicit wait as an illustrative choice, not a universal timeout. Change the link locator, expected title or content, and assertions to match the application and test framework. The WebDriverWait constructor and dependencies should match the Selenium Java version used by your project. See Selenium’s official guide to working with windows and tabs and the Java API references for getWindowHandles(), switchTo().window(), and WebDriverWait.

Why compare against the original set?

getWindowHandles() returns a set; do not treat its iteration order as a reliable way to identify the popup. Save the set before clicking and select the handle that appears afterward. This remains useful when more than two contexts are open, or when a test does not begin with just one.

Rank #2
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

How should I wait for a new tab?

Wait for the handle count to increase before searching for the new handle. Without the wait, the click can return before the browser has created the additional context. If the action could open several contexts, compare the current set with the saved set, then switch through the new handles and identify the intended page by a meaningful property such as its title or URL.

When should I use Selenium 4’s newWindow method?

Use newWindow when the test itself needs to create a fresh context. Selenium 4 and later provide methods that create and select a tab or window directly:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Yilador Webcam Cover 3 Pack, 0.03 inch Ultra Thin Laptop Camera Cover Slide
  • Note: Not suitable for MacBooks released after 2023 or devices with a protruding front camera; Not applicable to full-screen or notch-style tempered glass screen protectors; Do not use on the rear camera of the phone.
  • 💻 Why Do You Need a Webcam Cover Slide? — Safeguard your privacy by covering your webcam with our reliable webcam cover when not in use. Don't let anyone secretly watch you. Stay protected!
  • ✅ Thin & Stylish — Enhance your laptop's functionality and aesthetics with our 0.027" ultra-thin webcam covers. Seamlessly close your laptop while adding a touch of sophistication.
  • ✅ Fits Most Devices — Compatible with laptops, phones, tablets, desktops! Keep your privacy intact on Ap/ple, Mac/Book, iPh/one, iP/ad, H/P, L/novo, De/ll, Ac/er, As/us, Sa/msung devices.
  • ✅ 365 Days Protection — Our upgraded 3.0 adhesive ensures a strong hold that won't damage your equipment. Experience reliable, long-term privacy protection day in and day out.
driver.switchTo().newWindow(WindowType.TAB);
driver.switchTo().newWindow(WindowType.WINDOW);

This differs from a context opened by the application. For an application-triggered popup, wait for and discover the new handle before switching to it.

Situation Approach Why
An application action opens a tab or window Save the existing handle set, trigger the action, wait for a count increase, find the new handle, and switch The context is created asynchronously, and handle order should not be assumed.
Test code needs a fresh tab or window Use Selenium 4 or later’s newWindow(WindowType.TAB) or newWindow(WindowType.WINDOW) The method creates and selects the new context.

How do I close a popup and switch back to the parent?

Store the parent handle before switching to the child. When finished, call driver.close() to close only the currently selected context, then switch to the still-open parent with driver.switchTo().window(originalHandle).

Rank #4
AboveTEK Portable Laptop Lap Desk w/Retractable Left/Right Mouse Pad Tray, Non-Slip Heat Shield Tablet Notebook Computer Stand Table w/Sturdy Stable Work Surface for Bed Sofa Couch or Travel
  • Anti-Slip Surface - Transform your laptop into a mobile workstation with the AboveTEK portable laptop lap desk. The anti-slip surface provides a strong grip for laptops up to 15.6 inches(Diagonal), while the double rubber strip on the bottom ensures a stable display or typing experience on your lap, couch, or bed.
  • Retractable Mouse Pad - Retractable laptop mouse pad extends on both directions for the left/right handed with elevation along the edges for stopping mouse from falling off. The size of laptop tray is 14" X 9.7" and the size of mouse pad is 7.4" X 6.1".
  • Effective Heat Shield - The effective heat shield made of sturdy and thick material protects your laptop from overheating. Prioritizes your comfort and safety, an ideal lap pad or board for working anywhere.
  • EASY to Carry and Store - With an ergonomic and simplistic design, the lap desk is portable to store in a backpack. Only 15" in size, 2.2 lb of weight and with slim 0.6 inch thickness, it is ready to be easily carried around.
  • Widely Applicable - The smooth platform accommodates laptops and tablets up to 15.6 inches(Diagonal), making it a versatile accessory and one of the best gifts for mom, dad, students and professionals. Perfect for use as a laptop bed tray or tablet holder anywhere at home, library, or park.

After closing a selected context, do not issue further page commands until you have switched to an open handle. Selenium documents that staying on the closed context can trigger a No Such Window Exception. Use driver.quit() when the entire WebDriver session is finished; it ends the session and closes its windows.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common problems and fixes

  • No new handle found immediately after clicking: the browser may not have created the popup yet. Wait for the handle count to increase before searching.
  • The test is still interacting with the parent page: opening a new tab does not itself switch WebDriver’s selected context. Call driver.switchTo().window(newHandle).
  • The wrong tab was selected: do not rely on handle ordering. Compare with the saved pre-action set, then check the candidate page’s title or URL.
  • No Such Window Exception after closing a tab: the selected context was closed. Switch to a still-open handle before continuing.
  • Several popups opened: compare the full current handle set with the saved set, then inspect the new contexts one by one. Selenium’s guide recommends iterating over handles when more than two windows or tabs are involved.
  • Uncertainty about tabs versus windows: WebDriver exposes both through the same window-handle model, so the discovery and switching pattern is the same.

Or skip the browser setup

If your goal is to capture a page rather than test its interactive popup flow in a real browser session, ScreenshotNeo provides a website screenshot API and MCP server. Cookie banners, popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots, and the free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

One GET request can return a screenshot. See the ScreenshotNeo documentation for the API details.

Best Value
Sale
LAPGEAR Home Office Lap Desk – Pink, Fits 15.6” Laptops
  • Spacious Design: Measuring 21.1" wide and 12" deep, our lap desk comfortably fits most laptops up to 15.6". Extra room for accessories ensures convenience.
  • Enhanced Functionality: Packed with handy features, including a 5x9" precision tracking mouse pad and a built-in phone slot for seamless work or video calls. Plus, enjoy laptop support with the integrated device ledge.
  • Cool Comfort: Enjoy a stable surface with our lap desk's dual bolster cushion, designed for comfort and airflow, keeping your lap cool during extended use.
  • Durable Surface: Work with confidence on our lap desk's solid surface, featuring a blush pink color, ensuring optimal air circulation to prevent your laptop from overheating.
  • On-the-Go Convenience: With an integrated handle and lightweight design (2.14 lbs), our lap desk is portable for travel or moving around the house, offering flexibility in any space.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Sign up for 1,000 free screenshots a month, with no card required.

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.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.