Selenium WebDriver Java Framework Course Limited Time Offer for $50

Selenium WebDriver Java Framework Course Limited Time Offer for $50


How to handle multiple windows in selenium webdriver

When we have multiple windows in test automation, all we need to do is switching the focus from one window to another. Let us understand the same in the following way:

Window A has a link "Link1" and we need to click on the link (click event).

Window B displays and we perform some actions. 

The entire process can be fundamentally segregated into following steps:

Step 1 : Clicking on Link1 on Window A

A new Window B is opened.

Step 2 : Save reference for Window A

Step 3 : Create reference for Window B

Step 3 : Move Focus from Window A to Window B

Window B is active now

Step 3 : Perform Actions on Window B

Complete the entire set of Actions

Step 4 : Move Focus from Window B to Window A

Window A is active now

Let us understand the same with a small coding example.


import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class MultipleWindowsHandle {

     WebDriver driver;  
     public void setup() throws Exception {  
     driver=new FirefoxDriver();  
     String URL="";   
     public void test() throws Exception {   
     // Opening site  
     // Storing parent window reference into a String Variable  
     String Parent_Window = driver.getWindowHandle();    
      // Switching from parent window to child window   
     for (String Child_Window : driver.getWindowHandles())  
     // Performing actions on child window  
     List  dropdownitems=driver.findElements(By.xpath("//div[@id='DropDownitems']//div"));  
     int dropdownitems_Size=dropdownitems.size();  
     System.out.println("Dropdown item size is:"+dropdownitems_Size);  
     //Switching back to Parent Window  
     //Performing some actions on Parent Window  
      public void close() {