About Me

Page views

Powered by Blogger.

Followers

Tuesday, 5 May 2015

 

So how to handle windows popups using Selenium Webdriver ?

There are many cases, where a application displays multiple windows when you open a website.
Those are may be advertisements or may be a kind of information showing on popup windows. 
We can handle multiple windows using Windows Handlers in selenium webdriver.
 Steps:
 1: After opening the website, we need to get the main window handle by using driver.getWindowHandle();
The window handle will be in a form of lengthy alpha numeric. 

 2: We now need to get all the window handles by using driver.getWindowHandles(); 
 3: We will compare all the window handles with the main Window handles and perform the operation the window which we need.
This example shows how to handle multiple windows and close all the child windows which are not need. We need to compare the main window handle to all the other window handles and close them .
package dayTwo;

import java.util.Set;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

public class WindowExamples {
 static WebDriver driver;

 @Test
 public void test_CloseAllWindowsExceptMainWindow() {
  driver = new FirefoxDriver();
  // It will open Naukri website with multiple windows
  driver.get("http://www.naukri.com/");
  
  // To get the main window handle
  String windowTitle= getCurrentWindowTitle();
  String mainWindow = getMainWindowHandle(driver);
  Assert.assertTrue(closeAllOtherWindows(mainWindow));
  Assert.assertTrue(windowTitle.contains("Jobs - Recruitment"), "Main window title is not matching");
 }
  
 public String getMainWindowHandle(WebDriver driver) {
  return driver.getWindowHandle();
 }

 public String getCurrentWindowTitle() {
  String windowTitle = driver.getTitle();
  return windowTitle;
 }
 
 //To close all the other windows except the main window.
 public static boolean closeAllOtherWindows(String openWindowHandle) {
  Set<String> allWindowHandles = driver.getWindowHandles();
  for (String currentWindowHandle : allWindowHandles) {
   if (!currentWindowHandle.equals(openWindowHandle)) {
    driver.switchTo().window(currentWindowHandle);
    driver.close();
   }
  }
  
  driver.switchTo().window(openWindowHandle);
  if (driver.getWindowHandles().size() == 1)
   return true;
  else
   return false;
 }
}
 
 

0 comments:

Post a Comment

Popular Posts

Copyright © Learn Selenium Yourself | Powered by Blogger
Design by Duan Zhiyan | Blogger Theme by NewBloggerThemes.com