Selenium Window Handle Practice
Real applications open new tabs, pop-ups, payment gateways and third-party login windows — and load content asynchronously. This practice set combines both skills: 12 window-and-tab exercises, hands-on wait exercises, and 10 scenario questions, with solution code for every pattern.
Practice Sites
- The Internet – Multiple Windows and DemoQA – Browser Windows (new tab, new window, message window).
- The Internet – Dynamic Loading (hidden element and element added after load) and DemoQA – Dynamic Properties (enabled after 5 seconds, visible after 5 seconds).
- The NavTutorial Practice Hub.
Solution Patterns: Windows and Tabs
// 1. Switch to the window that opened after a click
String parent = driver.getWindowHandle();
driver.findElement(By.linkText("Click Here")).click();
new WebDriverWait(driver, Duration.ofSeconds(10))
.until(ExpectedConditions.numberOfWindowsToBe(2));
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(parent)) {
driver.switchTo().window(handle);
break;
}
}
System.out.println(driver.getTitle());
driver.close(); // closes only the current (child) window
driver.switchTo().window(parent); // always switch back after close()
// 2. Open a new tab or window yourself (Selenium 4)
// Selenium automatically switches to the newly created window.
driver.switchTo().newWindow(WindowType.TAB);
driver.get("https://www.selenium.dev/");
// 3. Close every child window, keep the parent
for (String handle : driver.getWindowHandles()) {
if (!handle.equals(parent)) {
driver.switchTo().window(handle);
driver.close();
}
}
driver.switchTo().window(parent);
// 4. Keep handles by name for complex flows
Map<String, String> windows = new LinkedHashMap<>();
windows.put("main", parent);
// … after opening the payment window:
// windows.put("payment", newHandle);
// driver.switchTo().window(windows.get("payment"));
After driver.close(), the driver has no current window until you switch — any command in between throws NoSuchWindowException. Theory: Alerts, Frames & Windows.
Window & Tab Exercises
Level 1 — Basics (0–1 year)
- Open and switch to a new tab: open a tab, verify its title, return to the parent, close both.
- Close one specific tab: open several, close only the one you choose, verify the rest remain.
- Child window: capture the parent handle, click a link that opens a window, switch, print the title, close it, return.
- Loop through tabs: open several tabs, print each title, close them one by one and finish on the parent.
Level 2 — Intermediate (1–3 years)
- Multiple child windows: open several, perform a different action in each, close selected ones.
- Switch back and forth: alternate between parent and child several times, verifying the active window's title every time.
- Close all child windows: keep only the parent open and continue the test.
- New tab without a link: use
switchTo().newWindow(WindowType.TAB)(Selenium 4) — orwindow.open()through JavaScriptExecutor — then fill a form there.
Level 3 — Advanced (3–5 years)
- Windows in parallel runs: make window handling thread-safe with one driver per thread (
ThreadLocal) so tests don't switch each other's windows. - Pop-up form: a pop-up window opens — switch to it, submit a form, verify the result in the parent.
- Named handles: store handles in a
Map<String, String>("main","payment","help") and switch by name. - Data-driven window flow: read test data from Excel, fill a form in the child window for each row, and return to the parent each time.
Solution Patterns: Waits
// Explicit wait — the default choice
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.elementToBeClickable(By.id("start"))).click();
wait.until(ExpectedConditions.invisibilityOfElementLocated(
By.id("loading")
));
String text = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.cssSelector("#finish h4")
)
).getText();
// Fluent wait — custom polling and ignored exceptions
Wait<WebDriver> fluent = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);
fluent.until(d ->
d.findElement(By.id("status"))
.getText()
.equals("Complete")
);
// Reusable helper for your BasePage
public WebElement waitForClickable(By locator, int seconds) {
return new WebDriverWait(driver, Duration.ofSeconds(seconds))
.until(ExpectedConditions.elementToBeClickable(locator));
}
Compare the three strategies side by side in the Selenium Wait Simulator.
Theory: Selenium Waits and Implicit vs Explicit vs Fluent.
Wait Exercises
Thread.sleep() — Learn Why Not
- On Dynamic Loading, click Start and use
Thread.sleep(5000)before reading the text. Note the run time. - Replace it with an explicit wait and compare the run time.
- Reduce the sleep to 2 seconds and watch it fail — then explain why sleeps fail on slower CI machines.
Implicit Wait
- Set
implicitlyWait(Duration.ofSeconds(10))and locate a slow-loading element. - Remove it and observe
NoSuchElementException. - Check an element that shouldn't exist with
findElements()and measure how long it takes with the implicit wait on — then explain why frameworks keep it at zero.
Explicit Wait
- Wait for visibility, clickability, a page title, specific text, and an alert.
- Wait for a loading spinner to disappear before clicking.
- Wait before a hover action on a menu that renders late.
- Build reusable wait helpers in a
BasePageand refactor your earlier exercises to use them.
Fluent Wait
- Create a FluentWait with a 20-second timeout, 2-second polling, ignoring
NoSuchElementException. - Wait until a status text changes to
"Complete". - Wait for an AJAX table to reach an expected number of rows with a custom lambda condition.
Real-Time Scenario Questions
- An element appears randomly depending on the server response. Which wait would you use, and why?
- The app works locally but loads slowly in QA. How do you synchronize without increasing every timeout?
- Buttons become clickable after background requests. How do you automate this without
Thread.sleep()? - Both implicit and explicit waits are configured. What problems can occur? (Unpredictable, longer wait times — keep implicit at 0.)
- A legacy framework has hundreds of
Thread.sleep()calls. How would you remove them safely? - A button is sometimes clickable and sometimes not. How do you make the test stable?
- An alert appears after an unknown time. How do you wait for it?
- Table rows load gradually after AJAX calls. Which condition proves the table is ready?
- Tests time out only in Jenkins. How do you investigate? See Test Passes Locally, Fails in Jenkins.
- Wait logic is repeated across the framework. How would you design reusable wait methods?
Senior Tester Tips
- Never use
Thread.sleep()as synchronization in a framework. - Use explicit waits for everything dynamic, and keep the implicit wait at zero — mixing the two makes timeouts unpredictable.
- Use a fluent wait (or a customized
WebDriverWait) when you need different polling or ignored exceptions. - Wait for the condition that proves the page is ready — a spinner gone, a row count, a status text — not for time to pass.
- Always switch back to a valid window after
close(), and wait for the new window to exist before switching.
From Real Projects
Synchronization mattered most for me when our Selenium suites ran in parallel and across Chrome and Firefox — timing that worked in a single run didn't always hold. Waiting for a specific condition, rather than a fixed pause, is what made scripts reliable on both browsers. On Canolog, the many forms and screens across sales, inventory, finance and service are where keeping page details in POM classes and reusable steps in a business library paid off. Always store the original window handle before opening a new tab or window.
Frequently Asked Questions
How do you switch between browser windows?
Save the parent handle with getWindowHandle(), wait for the new window, loop through getWindowHandles(), and switchTo().window(handle) for the one that isn't the parent.
How do you close only one tab?
Switch to it, call driver.close(), then switch back to a remaining window — the driver has no current window until you do.
close() vs quit()?
close() closes the current window; quit() closes all windows and ends the session.
Why is Thread.sleep() not recommended?
It always waits the full time — slowing every run — and still fails when the application is slower than expected, for example on CI.
When should a fluent wait be used?
When content loads at unpredictable times or re-renders while loading, and you need custom polling or ignored exceptions.
Related
- The Complete Selenium Practice Roadmap
- Frames & iFrames Practice · Alerts & Popups Practice
- Top 50 Selenium Interview Questions