Switch Windows Using Selenium WebDriver

Some web applications open a new window in order to section specific data entry or view.

Selenium can switch windows via the window handle.

The following is an example and must be configured for a specific website under test.
// Store the current window handle
String winHandleBefore = driver.getWindowHandle();
// Perform the click operation that opens new window
driver.findElement(By.LinkText("Open in New Window"));
// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
// Perform the actions on new window
// Do something here...
// Close the new window, if that window no more required
// Switch back to original browser (first window)

The above code clicks on a page link to open a new window.

The WebDriver will set the focus of the most recent window in which the test developer can perform actions on it after.

Finally, it closes the new window and switches back to the original window.





Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.