Handling Multiple Browsers or Tabs
How it works:
1. Setup & launch – set webdriver.chrome.driver and open a Chrome session.
2. Navigate – go to your test page (replace the URL).
3. Main handle – capture driver.getWindowHandle() for returning later.
4. Trigger – click the element that opens a new window.
5. Handles set – call driver.getWindowHandles() to get both main and child handles.
6. Switch – iterate the set, find the handle that isn’t the main one, and driver.switchTo().window(childHandle).
7. Interact – perform any reads or clicks in the child window.
8. Close child – driver.close() closes only the current window.
9. Return – driver.switchTo().window(mainWindowHandle) brings you back to the original window.
10. Teardown – driver.quit() ensures all windows are closed and the session ends.
Adjust the locators (By.xpath(…)), URLs, and any child-window interactions to match your application under test.
Program:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Set;
public class WindowHandlingExample {
public static void main(String[] args) throws InterruptedException {
// 1. Point to your ChromeDriver executable
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
// 2. Launch Chrome
WebDriver driver = new ChromeDriver();
try {
// 3. Navigate to the page with a link/button that opens a new window
driver.get("https://example.com/multiple-windows");
// 4. Store the handle of the main window
String mainWindowHandle = driver.getWindowHandle();
System.out.println("Main window handle: " + mainWindowHandle);
// 5. Trigger opening a new window (adjust locator as needed)
WebElement openNewWindowBtn = driver.findElement(
By.xpath("//button[@id='openWindow']"));
openNewWindowBtn.click();
// 6. Wait briefly for the new window to open
Thread.sleep(2000);
// 7. Get all window handles
Set<String> allWindowHandles = driver.getWindowHandles();
System.out.println("All window handles: " + allWindowHandles);
// 8. Switch to the newly opened window
for (String handle : allWindowHandles) {
if (!handle.equals(mainWindowHandle)) {
driver.switchTo().window(handle);
System.out.println("Switched to child window: " + handle);
break;
}
}
// 9. Perform actions in the child window
System.out.println("Child window title: " + driver.getTitle());
// e.g., click something or read some text
// WebElement childElement = driver.findElement(By.id("someElement"));
// System.out.println(childElement.getText());
// 10. Close the child window
driver.close();
System.out.println("Child window closed.");
// 11. Switch back to the main window
driver.switchTo().window(mainWindowHandle);
System.out.println("Switched back to main window: " + driver.getTitle());
} finally {
// 12. Close all browser windows and end the session
driver.quit();
}
}
}