Monday, 8 October 2018

Working on Multiple Windows on a Browser - Example to Practice

Working on Multiple Windows in a Browser:
=================================
To work on multiple windows we need to switch between windows by using window handles

Procedure:
Step 1: Firstly, we need to get window handles using "getWindowHandles()" command

Syntax:
Set pageHandles=driver.getWindowHandles();

It will return handles of all opened windows into a "Set" class

Step 2: Use Iterator class to read each window handle from "Set" class

Syntax:
Iterator winHandles= pageHandles.iterator();

Step 3: Rread each window handle into variable using Iterator class

Syntax:
String win1= winHandles.next();
String win2= winHandles.next();

Step 4:  To work on specified window we can use the following command:

driver.switchTo().window(window handle);

NOTE:  If we want to come back to first window, we can use below command

driver.switchTo().defaultContent();

Exp: Write script to read page titles while navigating between multiple windows

Script:
WebDriver driver= new FirefoxDriver();
driver.get("https://accounts.google.com/signin");
driver.manage().window().maximize();

//to read first window title
String pgTitle1=driver.getTitle();
System.out.println("1st page title is: "+pgTitle1);

//to click on Help
driver.findElement(By.linkText("Help")).click();

Thread.sleep(3000);
//to read opened window handles
Set pgHandles=driver.getWindowHandles();
//to read each window handle
Iterator winHandles=pgHandles.iterator();
//to read window handle into variable
String win1=winHandles.next();
String win2=winHandles.next();

System.out.println(win1);
System.out.println(win2);
//to focus on 2nd window
driver.switchTo().window(win2);
//to read second window title
String pgTitle2=driver.getTitle();
System.out.println("2nd page title is: "+pgTitle2);

No comments:

Post a Comment