Sunday 28 September 2014

Handling Multiple PopUp Browser Windows in WebDriver

There are situations when clicking on a link/button in a web page (from parent window) opens a new browser (called child window).
And the user wants to perform some operation on child window and gets back to parent window.

In the below example, we are clicking on FB share button which opens a new browser and after it opens we are verifying and coming back to parent window

Here is the code for that :


String parentWindowHandle = driver.getWindowHandle(); // save the current window handle.

  // FB Share Verification
  driver.findElement(fbShare).click();

  for(String winHandle :driver.getWindowHandles()){
   driver.switchTo().window(winHandle);
   if(driver.getTitle().equals("Facebook")){
    logger.info("Title of the new popUp window: " + driver.getTitle());
    logger.info("You are in FaceBook window");
    break;
   } else{
    logger.info("Title of the page after - switchingTo: " + driver.getTitle());
   }
  }
  driver.close();
  driver.switchTo().window(parentWindowHandle);  // switch back to parent window
}

Here,

- getWindowHandle() is a method in WebDriver class is used to get the target locator of the window or frame.

- getWindowHandles() is again a method in WebDriver class which helps in switching to a different window.

driver.switchTo().window(parentWindowHandle) is used to switch to a specific window handle.

Just embed this code snippet wherever switching to a different window condition comes to you and you can easily switch back.

No comments:

Post a Comment