Understanding Selenium WebDriver API Commands (Part 6)

Multiple Windows Handling in Selenium

Sometimes we face this scenario when clicking a link redirects to a new page in a different browser window. Performing an action on multiple windows is achievable using window handles in Selenium WebDriver. WebDriver provides two methods to get the window handle:

This method will return a string value for the window handle of the current window in focus.

This method will return a Set <String> for all the window handles of windows that are opened in that session.

Initially, the focus is on the parent window. To switch the focus to child window, we can use the following command:

driver.switchTo().window(handle);       

Here, handle is the String value for the window handle.

Once you have performed an action on child window, you can close it using the following command:

driver.close();

Usage example code

driver.get(“http://www.360logica.com/blog/”);

String parentWindow = driver.getWindowHandle();

driver.switchTo().frame(“twitter-widget-1”);

driver.findElement(By.id(“b”)).click();

Thread.sleep(2000);

Set<String> windowHandles = driver.getWindowHandles();

for(String handle : windowHandles)

{

driver.switchTo().window(handle);

new WebDriverWait(driver, 20L).until(ExpectedConditions

.presenceOfElementLocated(By.xpath(“//input[@type=’submit’]”)));

}

// Close the child window

driver.close();

// Switch to the parent window

driver.switchTo().window(parentWindow);

Read Also: Understanding Selenium WebDriver API Commands (Part 5)

SHARE THIS

Get A Free Quote

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.