Selenium WebDriver Java Framework Course Limited Time Offer for $20

Selenium WebDriver Java Framework Course Limited Time Offer for $20

 

Print

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;  
     @Before  
     public void setup() throws Exception {  
     driver=new FirefoxDriver();  
     String URL="http://www.seleniummaster.com";   
     driver.get(URL);  
     driver.manage().window().maximize();  
     }  
     @Test  
     public void test() throws Exception {   
     // Opening site  
     driver.findElement(By.xpath("//img[@alt='SeleniumMasterLogo']")).click();  
     // 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())  
     {  
     driver.switchTo().window(Child_Window);  
     // Performing actions on child window  
     driver.findElement(By.id("dropdown_txt")).click();  
     List  dropdownitems=driver.findElements(By.xpath("//div[@id='DropDownitems']//div"));  
     int dropdownitems_Size=dropdownitems.size();  
     System.out.println("Dropdown item size is:"+dropdownitems_Size);  
     ((WebElementdropdownitems.get(1)).click();  
     driver.findElement(By.xpath("//*[@id='anotherItemDiv']")).click();  
     }  
     //Switching back to Parent Window  
     driver.switchTo().window(Parent_Window);  
     //Performing some actions on Parent Window  
     driver.findElement(By.className("btn_style")).click();  
     }  
      @After  
      public void close() {  
      driver.quit();  
      }   
     }