In this post, we will see how to handle multiple windows using Selenium WebDriver. In real time, we face many scenarios, where an application throws multiple popups. We can easily achieve this using Windows Handles in Selenium WebDriver. We use ‘Switch To’ method which allows us to switch control from one window to other.

Here is a program which handles multiple windows. Given clear explanation in the comments section within the program itself. Please go through it to understand the flow.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package softwareTestingMaterial;
import org.testng.annotations.Test;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class MultipleWindowsClass{
@Test
public void testMultipleWindows() throws InterruptedException{
System.setProperty(“webdriver.gecko.driver”, System.getProperty(“user.dir”)+“\\src\\test\\java\\drivers\\geckodriver.exe”);
// To open browser
WebDriver driver=new FirefoxDriver();
// To maximize browser
driver.manage().window().maximize();
// To open Naukri website with multiple windows
driver.get(“http://www.naukri.com/”);
// It will return the parent window name as a String
String mainWindow=driver.getWindowHandle();
// It returns no. of windows opened by WebDriver and will return Set of Strings
Set<String> set =driver.getWindowHandles();
// Using Iterator to iterate with in windows
Iterator<String> itr= set.iterator();
while(itr.hasNext()){
String childWindow=itr.next();
   // Compare whether the main windows is not equal to child window. If not equal, we will close.
if(!mainWindow.equals(childWindow)){
driver.switchTo().window(childWindow);
System.out.println(driver.switchTo().window(childWindow).getTitle());
driver.close();
}
}
// This is to switch to the main window
driver.switchTo().window(mainWindow);
}
}

If you have any queries, please comment below.

  • Selenium Tutorial
  • Selenium Interview Questions
  • TestNG Tutorial
  • TestNG Interview Questions