Operations 4 min read

How to Manage Three Browser Windows in Selenium Java – A Complete Walkthrough

When automating a download flow with Selenium Java, you may encounter three browser windows; this article explains how to enumerate all handles, switch to each window, perform actions, and close them safely using explicit checks and WebDriver commands.

FunTester
FunTester
FunTester
How to Manage Three Browser Windows in Selenium Java – A Complete Walkthrough

While learning Selenium 2 with Java, the author faced a scenario where clicking a link opened three browser windows instead of the expected two. Existing tutorials only covered two‑window handling, so the author examined all window handles to devise a robust solution.

The method downloadResources(WebDriver driver, boolean key) first logs in as either a teacher or a student, then clicks the "精品资源" link to open the resource page. It stores the original window handle in homehandle and retrieves the full set of handles with driver.getWindowHandles().

It iterates over each handle, skipping the original one, and switches to the newly opened resource window. Inside that window it clicks several elements identified by XPath to navigate to the actual download links, pauses with Thread.sleep(2000), and then captures the handle of the download popup ( news).

Another loop processes the download popup window: it switches to any handle that is neither the download popup nor the original window, clicks the final download link, accepts the alert, and closes the popup. A second loop returns to the resource window, logs a message, and closes it as well.

Finally, the code loops over the original set of handles again, finds the original home window, switches back, logs a return message, waits, and calls driver.quit() to end the session.

This step‑by‑step handling ensures that all three windows are correctly identified, interacted with, and closed, preventing orphaned browsers and making the automation reliable.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaAutomationtestingSeleniumWebDriverwindow-handles
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.