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

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


- 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.