Wait for a Popup Window That Opens Late
A reusable wait that returns the handle of a window opened asynchronously (OAuth, payment, print preview), with a timeout and clean switching back.
Problem
Clicking “Sign in with Provider” or “Pay now” does not open the popup immediately. The app first calls its backend, then runs window.open() a second or two later. Code that reads the window handles straight after the click sees only the original window, and code that sleeps first is slow and still flaky. Sometimes the popup also closes itself when done, and the test needs to know when that has happened.
Solution
Capture the existing handles before the action, then use a custom wait condition that returns the new handle once it appears. A matching condition waits for the popup to close. This builds on the basic switch to a new tab pattern and packages it as a reusable helper for slow, asynchronous popups.
public static String waitForNewWindow(WebDriver driver, Set<String> before, Duration timeout) { return new WebDriverWait(driver, timeout) .withMessage("No new window opened") .until(d -> d.getWindowHandles().stream() .filter(h -> !before.contains(h)) .findFirst().orElse(null)); // null means "keep waiting"}
public static void waitForWindowToClose(WebDriver driver, String handle, Duration timeout) { new WebDriverWait(driver, timeout) .until(d -> !d.getWindowHandles().contains(handle));}
String main = driver.getWindowHandle();Set<String> before = driver.getWindowHandles();
driver.findElement(By.id("sign-in-with-provider")).click();String popup = waitForNewWindow(driver, before, Duration.ofSeconds(15));
driver.switchTo().window(popup);driver.findElement(By.id("username")).sendKeys("test.user");driver.findElement(By.id("password")).sendKeys(System.getenv("PROVIDER_PASSWORD"));driver.findElement(By.cssSelector("button[type='submit']")).click();
waitForWindowToClose(driver, popup, Duration.ofSeconds(15)); // provider closes itselfdriver.switchTo().window(main);def wait_for_new_window(driver, before, timeout=15): def new_handle(d): fresh = set(d.window_handles) - before return fresh.pop() if fresh else False return WebDriverWait(driver, timeout).until(new_handle, "No new window opened")
def wait_for_window_to_close(driver, handle, timeout=15): WebDriverWait(driver, timeout).until(lambda d: handle not in d.window_handles)
main = driver.current_window_handlebefore = set(driver.window_handles)
driver.find_element(By.ID, "sign-in-with-provider").click()popup = wait_for_new_window(driver, before)
driver.switch_to.window(popup)driver.find_element(By.ID, "username").send_keys("test.user")driver.find_element(By.ID, "password").send_keys(os.environ["PROVIDER_PASSWORD"])driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
wait_for_window_to_close(driver, popup)driver.switch_to.window(main)async function waitForNewWindow(driver, before, timeout = 15000) {return driver.wait(async () => { const handles = await driver.getAllWindowHandles(); return handles.find((h) => !before.has(h)); // undefined means "keep waiting"}, timeout, 'No new window opened');}
async function waitForWindowToClose(driver, handle, timeout = 15000) {await driver.wait(async () => !(await driver.getAllWindowHandles()).includes(handle), timeout);}
const main = await driver.getWindowHandle();const before = new Set(await driver.getAllWindowHandles());
await driver.findElement(By.id('sign-in-with-provider')).click();const popup = await waitForNewWindow(driver, before);
await driver.switchTo().window(popup);await driver.findElement(By.id('username')).sendKeys('test.user');await driver.findElement(By.id('password')).sendKeys(process.env.PROVIDER_PASSWORD);await driver.findElement(By.css("button[type='submit']")).click();
await waitForWindowToClose(driver, popup);await driver.switchTo().window(main);public static string WaitForNewWindow(IWebDriver driver, ISet<string> before, TimeSpan timeout){ var wait = new WebDriverWait(driver, timeout) { Message = "No new window opened" }; return wait.Until(d => d.WindowHandles.FirstOrDefault(h => !before.Contains(h))); // null = keep waiting}
public static void WaitForWindowToClose(IWebDriver driver, string handle, TimeSpan timeout) => new WebDriverWait(driver, timeout).Until(d => !d.WindowHandles.Contains(handle));
var main = driver.CurrentWindowHandle;var before = driver.WindowHandles.ToHashSet();
driver.FindElement(By.Id("sign-in-with-provider")).Click();var popup = WaitForNewWindow(driver, before, TimeSpan.FromSeconds(15));
driver.SwitchTo().Window(popup);driver.FindElement(By.Id("username")).SendKeys("test.user");driver.FindElement(By.Id("password")).SendKeys(Environment.GetEnvironmentVariable("PROVIDER_PASSWORD"));driver.FindElement(By.CssSelector("button[type='submit']")).Click();
WaitForWindowToClose(driver, popup, TimeSpan.FromSeconds(15));driver.SwitchTo().Window(main);Why It Works
WebDriverWait.until keeps polling while the condition returns null or false and returns the first truthy value. Returning the handle itself means one call both waits and gives you what you need, with no second lookup and no race. Diffing against the handles captured before the click identifies the popup regardless of how many windows are already open or what order the driver lists them in.
Gotchas
- Capture
beforebefore the click, not after. If you read handles after clicking, a fast popup is already in the set and the wait never finds a “new” one. - Do not touch the popup’s handle after it closes. Once the provider closes its window, any command still aimed at it throws
NoSuchWindowException. Switch back tomainimmediately afterwaitForWindowToClose. - Popup blockers. If
window.open()runs too long after the user gesture, some browsers block it. In that case the wait times out; the fix is in the app (open the window synchronously, then navigate it) or the browser options, not a longer timeout. - Same-tab fallbacks. Some OAuth libraries fall back to a full-page redirect on narrow screens or when popups are blocked. If your mobile emulation tests time out here, check whether the current tab navigated instead.
- Event-driven alternative. With WebDriver BiDi you can subscribe to
browsingContext.contextCreatedand get notified the moment a window opens, without polling. Polling handles is simpler and works everywhere, so it remains the default.
Learn the theory
- Windows and Tabs Handle multiple browser windows and tabs, switch between them, and manage popup windows.
- Custom Wait Conditions Write your own expected conditions with lambdas and classes, wait for attribute and text changes, element counts, JavaScript state, network idleness via BiDi, and compose conditions cleanly.