Window handles (getWindowHandles) in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; import java.util.Set; public class WindowHandlesTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "path/to/chromedriver"); WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); try { // Step 1: Open main page driver.get("https://example.com/testpage"); String originalWindow = driver.getWindowHandle(); // Step 2: Click link that opens new window driver.findElement(By.id("open-new-window")).click(); // Step 3: Wait for new window wait.until(driver1 -> driver1.getWindowHandles().size() > 1); // Step 4: Get all window handles Set<String> allWindows = driver.getWindowHandles(); // Step 5: Switch to new window for (String windowHandle : allWindows) { if (!windowHandle.equals(originalWindow)) { driver.switchTo().window(windowHandle); break; } } // Step 6: Verify new window title String newWindowTitle = driver.getTitle(); if (!newWindowTitle.equals("New Window Title")) { throw new AssertionError("New window title mismatch. Expected: 'New Window Title', Found: '" + newWindowTitle + "'"); } // Step 7: Close new window driver.close(); // Step 8: Switch back to original window driver.switchTo().window(originalWindow); // Step 9: Verify original window title String originalTitle = driver.getTitle(); if (!originalTitle.equals("Original Window Title")) { throw new AssertionError("Original window title mismatch. Expected: 'Original Window Title', Found: '" + originalTitle + "'"); } System.out.println("Test passed: Window handles switched and verified successfully."); } finally { driver.quit(); } } }
This code starts by opening the main test page and saving the original window handle. It clicks a link that opens a new window. Then it waits until there are more than one window handles available.
It collects all window handles and switches to the one that is not the original. It verifies the new window's title matches the expected value.
After verification, it closes the new window and switches back to the original window. It then verifies the original window's title to confirm the switch back was successful.
Finally, it quits the driver to close all browser windows. The code uses explicit waits and proper window handle management to avoid errors.
Now add data-driven testing with 3 different links that open different new windows and verify their titles.
Practice
getWindowHandles() return when called?Solution
Step 1: Understand the purpose of
This method is designed to return all window handles for every open window or tab in the current browser session.getWindowHandles()Step 2: Identify the return type
The method returns a Set of Strings, each representing a unique window handle (ID).Final Answer:
A set of all open window handles (IDs) in the current WebDriver session -> Option AQuick Check:
getWindowHandles() = all window IDs [OK]
- Confusing getWindowHandles() with getWindowHandle() which returns one handle
- Expecting a list or array instead of a set
- Thinking it returns page titles or URLs
Solution
Step 1: Check the return type of getWindowHandles()
The method returns a Set of Strings, so the variable must be declared as Set<String>.Step 2: Verify method name and syntax
The correct method is getWindowHandles() (plural), and it belongs to the WebDriver instance named driver.Final Answer:
Set<String> handles = driver.getWindowHandles(); -> Option CQuick Check:
Correct syntax uses Set<String> and getWindowHandles() [OK]
- Using List instead of Set for window handles
- Calling getWindowHandle() instead of getWindowHandles()
- Assigning to a String instead of a collection
Set<String> handles = driver.getWindowHandles(); System.out.println(handles.size());
If the browser has 3 tabs open, what will be printed?
Solution
Step 1: Understand what getWindowHandles() returns
It returns a set containing all window handles for every open tab or window.Step 2: Determine the size of the set
Since there are 3 tabs open, the set will contain 3 unique handles, so size() returns 3.Final Answer:
3 -> Option DQuick Check:
Number of tabs = size of handles set = 3 [OK]
- Assuming size() returns 1 for current window only
- Expecting an exception if multiple tabs exist
- Confusing getWindowHandles() with getWindowHandle()
Set<String> handles = driver.getWindowHandles(); String newWindow = handles.iterator().next(); driver.switchTo().window(newWindow);
But it always switches to the original window. What is the likely problem?
Solution
Step 1: Analyze iterator().next() behavior on a Set
Calling iterator().next() on a Set returns the first element, which is usually the original window handle.Step 2: Understand why it switches to original window
Since newWindow is assigned the original window handle, switching to it does not change the window.Final Answer:
Using iterator().next() returns the first handle, which is the original window -> Option BQuick Check:
iterator().next() = first handle (original window) [OK]
- Assuming iterator().next() gives the new window handle
- Thinking switchTo().window() needs window title
- Not checking if getWindowHandles() is empty
String originalHandle = driver.getWindowHandle(); and Set<String> allHandles = driver.getWindowHandles();, which code correctly switches to the new window?Solution
Step 1: Identify the original window handle
We have the original window handle stored inoriginalHandle.Step 2: Loop through all handles to find the new one
Iterate over all handles and switch to the one that is not equal to the original handle.Step 3: Switch to the new window
Once found, calldriver.switchTo().window(handle)and break the loop.Final Answer:
for (String handle : allHandles) { if (!handle.equals(originalHandle)) { driver.switchTo().window(handle); break; } } -> Option AQuick Check:
Switch to handle != originalHandle [OK]
- Switching to first handle without checking if it's original
- Using toArray()[0] which may be original window
- Switching to originalHandle instead of new window
Ready to prove it?
Pass the test and this pattern moves unknown
