রবিবার, ২৫ অক্টোবর, ২০১৫

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.
Step 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
Step 2: We now need to get all the window handles by using driver.getWindowHandles();
Step 3: We will compare all the window handles with the main Window handles and perform the operation the window which we need.
Click here to view Performing operations on multiple windows using reusable methods.
The below 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 com.pack;

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;
 }
}
The below image will show you the multiple windows that open in the application. It has now open total of three windows (One is main window and other two are child windows)

কোন মন্তব্য নেই:

একটি মন্তব্য পোস্ট করুন