Home Guide How to handle multiple windows in Selenium?

How to handle multiple windows in Selenium?

By Neha Vaidya, Community Contributor -

Software testing plays a vital role in creating error-free products that offer seamless user experiences. Therefore, it is essential to test the software before putting it into production.

As technology advances, it is necessary to adopt automation testing into the development pipeline. Selenium is the most widely used framework for automated software testing of a website. Every website must be tested by putting it through multiple real-world user scenarios. One such scenario is the handling of multiple windows. This article will discuss how to automate this action with Selenium so that the website’s behavior can be monitored by testers.

Handling Multiple Windows in Selenium

The user scenario being automated here is: Open a new tab and then switch back to the last window to complete the other pending activities. In such scenarios, Selenium helps to handle multiple windows through window handlers and javascript executors.

What is a window handle?

It is a unique identifier that holds the address of all the windows. Think of it as a pointer to a window, which returns the string value. It is assumed that each browser will have a unique window handle. This window handle function helps to retrieve the handles of all windows.

Syntax

  1. get.windowhandle(): This method helps to get the window handle of the current window
  2. get.windowhandles(): This method helps to get the handles of all the windows opened
  3. set: This method helps to set the window handles in the form of a string. set<string> set= driver.get.windowhandles()
  4. switch to: This method helps to switch between the windows
  5. action: This method helps to perform certain actions on the windows

These are some of the methods that will be used to handle multiple windows in Selenium.


Read More: Getting Started with Selenium and Javascript: Tutorial


Example of handling multiple windows

Scenario: Navigate to the Browserstack home page. This is the parent window. From the parent window, let’s see how to handle the child windows and then again navigate back to the parent windows.

Steps to execute:

  1. Get the handle of the parent window using the command: String parentWindowHandle = driver.getWindowHandle();
  2. Print the window handle of the parent window.
  3. Find the element on the web page using an ID which is an element locator.
  4. Open multiple child windows.
  5. Iterate through child windows.
  6. Get the handles of all the windows that are currently open using the command: Set<String> allWindowHandles = driver.getWindowHandles(); which returns the set of handles.
  7. Use the SwitchTo command to switch to the desired window and also pass the URL of the web page.

Refer to the complete program below.

import java.util.Iterator; 
import java.util.Set; 
import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class WindowHandle_Demo { 
public static void main(String[] args) throws Exception {


System.setProperty("webdriver.chrome.driver","Path to the driver"); 
WebDriver driver = new ChromeDriver();

driver.manage().window().maximize();

// Load the website
driver.get("http://www.naukri.com/");

// It will return the parent window name as a String
String parent=driver.getWindowHandle();

Set<String>s=driver.getWindowHandles();

// Now iterate using Iterator
Iterator<String> I1= s.iterator();

while(I1.hasNext())
{

String child_window=I1.next();


if(!parent.equals(child_window))
{
driver.switchTo().window(child_window);

System.out.println(driver.switchTo().window(child_window).getTitle());

driver.close();
}

}
//switch to the parent window
driver.switchTo().window(parent);

}
}

Output:

Handling multiple windows in Selenium

On executing the parent window handle, it will open multiple child windows and then navigate back to the final window handle.

Run Selenium Tests on Real Device Cloud for Free

Now let’s perform some actions on the Browserstack website.

  • Use the javascriptexecutor to scroll down through a page.
  • Find the element using XPath and send keys (which is of the form string) to that particular element location.
  • Declare the web element Link to click on a particular link on the page. In this case, the link must open in a new window.
  • Get the window handles of all the windows and print them in a sequential manner.
  • Switch to the parent window and check if the title matches. If it does, scroll down the page using the javascriptexecutor.
  • Find another element on the web page using the element locator and specify the position of the new window.
  • Switch back to the parent window and scroll down through the page.


Code Snippet

import java.util.Set; 
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor; 
import org.openqa.selenium.Keys; 
import org.openqa.selenium.Point; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.chrome.ChromeDriver; 
import org.openqa.selenium.interactions.Actions; 

public class selenium { public static void main(String[] args) throws Exception 
{ 
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\chromedriver.exe"); 
WebDriver driver = new ChromeDriver(); 
driver.get("https://www.browserstack.com/"); 
String title = driver.getTitle(); System.out.println(title);

JavascriptExecutor js = (JavascriptExecutor) driver; 
driver.findElement(By.xpath("//span[contains(text(),'Solutions')]")).click();
driver.findElement(By.xpath("//a[contains(text(),'Geolocation Testing')]")).click();
js.executeScript("window.scrollBy(0,40)"); 

WebElement link = driver.findElement(By.xpath("//a[@id='product-menu-toggle']//span[@class='account-down-caret']//*[local-name()='svg']")); 
Actions newwin = new Actions(driver); 
newwin.keyDown(Keys.SHIFT).click(link).keyUp(Keys.SHIFT).build().perform(); 
//Thread.sleep(2000); 
//js.executeScript("window.scrollBy(0,400)"); 
Thread.sleep(3000); 
Set<String> windows = driver.getWindowHandles(); 
System.out.println(windows); 
System.out.println("a1"); 
for (String window : windows) 
{ 
driver.switchTo().window(window); 
if (driver.getTitle().contains("Most Reliable App & Cross Browser Testing Platform | Browserstack")) 
{ 
System.out.println("a2"); 
js.executeScript("window.scrollBy(0,1000)"); 
System.out.println("b1");
driver.findElement(By.xpath("//a[@id='logo']//*[local-name()='svg']")).click();

driver.findElement(By.xpath("//a[@id='signupModalButton']")).click(); 
driver.manage().window().setPosition(new Point(2000, 0)); 
} 
} 
Thread.sleep(3000); 
Set<String> windows1 = driver.getWindowHandles(); 
System.out.println(windows1); 
System.out.println("a3"); 
for (String window : windows1) 
{ 
driver.switchTo().window(window); 
System.out.println("a4"); 
js.executeScript("window.scrollBy(0,400)"); 
} 
} 
}

On executing the code above, it will launch multiple windows and the window handle will be retrieved. Run the code, automate user navigation through multiple windows, and ensure the website works perfectly in real user conditions. With Selenium WebDriver, ensure that websites offer an optimal user experience in all possible circumstances.

BrowserStack Logo Run Selenium Tests on 2000+ Browsers & Devices Get Started Free