How to Handle Multiple Windows in Selenium?

Last updated on Oct 17,2024 112.1K Views

How to Handle Multiple Windows in Selenium?

edureka.co

In this rapidly developing world of technology, one must always find ways to keep up with the time. As the world is evolving towards software development, testing plays a vital role in making the process defect-free. Selenium Testing Course is one such tool that helps in finding bugs and resolving them. This article on How to handle multiple windows in Selenium gives you an idea about how you can handle multiple windows while testing an application.

So, we’ll first begin by taking a look at the topics that we’ll be covering in this article:

So, before we get to know more about handling multiple windows in Selenium simultaneously, we’ll see what Selenium Webdriver is and learn how it functions.

What is Selenium Webdriver?

I bet most of the software testers out there must have worked with this amazing tool which makes their lives easier, and for those who don’t know what is Selenium, I’ll help you take your first baby steps in exploring this tool.

Selenium is an automation tool whose sole purpose is to test web applications developed by any organization. Now, what’s so fascinating about this tool which makes it popular?

Now let’s see how we can test an application using Selenium.

How to Run a Test Case in Selenium?

To test any application in Selenium, we follow certain procedures which eventually helps in performing the desired tasks.

The basic pre-requisites to run a test-case are:

Pre-requisites to Run Selenium Test-Case

Check out this article on how to set up Selenium to get an end to end guidance on the installation process.

So, in order to test an application, we need to know the basics of the programming language, which is Java in our case. So first, 

Take a look at this video to get understand each and every nuance about testing an application.

How to Write & Run a Test Case in Selenium | Selenium Tutorial | Selenium Training | Edureka

This video will give you an introduction to an automated software testing tool – Selenium and help you understand how to write and run a test case.

So, once we know how to run a test case in Selenium, we’ll try altering the process by working across multiple windows simultaneously. To do that we’ll see a few functions which help us doing it.

Here is a test Automation Engineer Course available who can provide the intelligence and expertise to easily create Automation Engineer systems.

How to Handle Multiple Windows in Selenium?

Now, what is a window handle function? How to handle multiple windows in Selenium while testing an application? Well, this will answer all your questions.

Related Learning: Desired Capabilities in Selenium

What is a window handle? 

A window handle is a unique identifier that holds the address of all the windows. This is basically a pointer to a window, which returns the string value. This window handle function helps in getting the handles of all the windows. It is guaranteed that each browser will have a unique window handle.

Syntax

These are a few new functions we’ll be seeing in this demo. Apart from these, the rest of the functions help in automating the process. 

How to Handle Multiple Windows in Selenium Webdriver | Selenium Certification Training | Edureka

This video will help you understand how to handle multiple windows when you are testing an application using Selenium.

 

Example of Window Handles in Selenium

In this demo section, we’ll automate a few websites and check how to handle multiple windows.

We’ll automate pages such as,

Now, we’ll first start by testing the webpage ToolsQA


package selenium;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class demo1 {
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "D:chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://toolsqa.com/automation-practice-switch-windows/");
WebElement clickElement = driver.findElement(By.id("button1"));

for(int i = 0; i < 3; i++)
{
clickElement.click();
Thread.sleep(3000);
}

}
}

Next step, we’ll add on a few more commands and notice the change in the execution.

  • This is almost similar to the first project except that we need to print the window handle of the parent and the child windows.
  • Get the handle of the parent window using the command: String parentWindowHandle = driver.getWindowHandle();
  • Print the window handle of the parent window.
  • Find the element on the web page using an ID which is an element locator.
  • Open multiple child windows.
  • Iterate through child windows.
  • Pause the execution for a few seconds using the sleep command Thread.sleep(3000) where the time is specified in nanoseconds.
  • 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. 
  • Print the handles of all the windows.

package selenium;

import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class demo2 {
public static void main(String[] args) throws InterruptedException
{

System.setProperty("webdriver.chrome.driver", "D:chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://toolsqa.com/automation-practice-switch-windows/");
String parentWindowHandle = driver.getWindowHandle();
System.out.println("Parent window's handle -> " + parentWindowHandle);
WebElement clickElement = driver.findElement(By.id("button1"));

for(int i = 0; i < 3; i++)
{
clickElement.click();
Thread.sleep(3000);
}

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

for(String handle : allWindowHandles)
{
System.out.println("Window handle - > " + handle);
}

}

}

Now, we’ll customize the web page by adding a few more commands to the above program.

  • In this program, we’ll test the same web page ToolsQA and pass another URL to the parent window.
  • Instantiate the browser driver to the new Chromedriver.
  • Get the window handle of the parent window and print it.
  • Find the element on the page using an ID which is an element locator.
  • Use for loop to iterate the number of child windows being created.
  • Get the handles of all the windows opened.
  • Print the window handle of the first window.
  • Use the SwitchTo command to switch to the desired window and also pass the URL of the web page “google.com” to the current window. 

package selenium;

import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class demo4 {

public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver", "D:chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://toolsqa.com/automation-practice-switch-windows/");
String parentWindowHandle = driver.getWindowHandle();
System.out.println("Parent window's handle -> " + parentWindowHandle);
WebElement clickElement = driver.findElement(By.id("button1"));

for(int i = 0; i < 3; i++)
{
clickElement.click();
Thread.sleep(3000);
}

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

for(String handle : allWindowHandles)
{
System.out.println("Switching to window - > " + handle);
System.out.println("Navigating to google.com");
driver.switchTo().window(handle); //Switch to the desired window first and then execute commands using driver
driver.get("http://google.com");
}

}
}

After this, we’ll see how we can alter the child window without a change in the parent window.

  • The process is almost similar to the previous program but just that after passing the URL, google.com, we will be switching to the parent window and close it.
  • After this, we will define the window handle of the last window and switch to this window and pass the URL of the ToolsQA page. So that this URL opens only in the last window and the other two child windows will still be showing google.com page.

package selenium;

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

public class demo5 {
public static void main(String[] args) throws InterruptedException
{

System.setProperty("webdriver.chrome.driver", "D:chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://toolsqa.com/automation-practice-switch-windows/");
String parentWindowHandle = driver.getWindowHandle();
System.out.println("Parent window's handle -> " + parentWindowHandle);
WebElement clickElement = driver.findElement(By.id("button1"));

for(int i = 0; i < 3; i++)
{
clickElement.click();
Thread.sleep(3000);
}

Set<String> allWindowHandles = driver.getWindowHandles();
String lastWindowHandle = "";
for(String handle : allWindowHandles)
{
System.out.println("Switching to window - > " + handle);
System.out.println("Navigating to google.com");
driver.switchTo().window(handle); //Switch to the desired window first and then execute commands using driver
driver.get("http://google.com");
lastWindowHandle = handle;
}

//Switch to the parent window
driver.switchTo().window(parentWindowHandle);
//close the parent window
driver.close();
//at this point there is no focused window, we have to explicitly switch back to some window.
driver.switchTo().window(lastWindowHandle);
driver.get("http://toolsqa.com");
}
}

Now, we’ll test one of the top job portals Naukri.com

  • Set the system property to Chromedriver and specify its path
  • Instantiate the webdriver to the new chromedriver
  • Get the URL of the web page and maximize the page
  • Get the window handle of the parent window
  • Get the window handles of all the windows
  • Next, we have declared an object of type iterator to use it for switching to the child window and perform actions on it
  • We check if the main window is equal to the child window or not, if(!mainweb.equals(child)). If the main window is not equal to the child window, condition holds and we switch to the next child window. 

package selenium;
import org.testng.annotations.Test;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class MultipleWindowsClass{
@Test
public void testMultipleWindows() throws InterruptedException{
System.setProperty("webdriver.chrome.driver", "D:chromedriver.exe");
// To open browser
WebDriver driver = new ChromeDriver();
// 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);
}
}

Next, we’ll perform some actions on our official website edureka.co

  • We’ll initialize the webdriver to the new chromedriver.
  • Get the URL of the webpage.
  • We’ll use the JavaScriptExecutor, it is an interface which provides a mechanism to execute Javascript through the Selenium WebDriver.
  • Get the window handle of the parent window.
  • Find the element using XPath, which is an element locator and send keys to a particular location on the web page.
  • Scroll down through the page using the javascriptexecutor command: js.executeScript(“window.scrollBy(X-axis, Y-axis)”);
  • Get the handles of all the windows and print it.
  • Next, we have declared an object of type iterator to use it for switching to the child window and perform actions on it.
  • We check for this condition if(!mainweb.equals(child)), if this condition holds, we switch to the child window and also print the title of it.

package selenium;

import java.util.Iterator;
import java.util.Set;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class demo3 {

public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.chrome.driver","S:chromedriver.exe");
WebDriver driver = new ChromeDriver();
JavascriptExecutor js = (JavascriptExecutor) driver;
driver.get("https://www.edureka.co/community");
String mainweb = driver.getWindowHandle();
driver.findElement(By.xpath("//a[@class='qa-logo-link edureka']")).sendKeys(Keys.SHIFT,Keys.ENTER);
Thread.sleep(100);
js.executeScript("window.scrollBy(0,400)");
Set <String> set = driver.getWindowHandles();
System.out.println(set);
Iterator <String> itr = set.iterator();
while(itr.hasNext())
{
js.executeScript("window.scrollBy(0,400)");
String child = itr.next();
if(!mainweb.equals(child))
{
driver.switchTo().window(child);
System.out.println(driver.switchTo().window(child).getTitle());
// driver.close();
}
}
driver.switchTo().window(mainweb);

}

}

Next, we’ll automate the same webpage by customizing it.

  • The process is almost similar to the previous one but in this, we print the title of the current page.
  • Use the javascriptexecutor to scroll down through a page.
  • Find the element using the element locator 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 and in this case, we want the link to open in a new window.
  • Pause the execution for a few seconds after this.
  • Get the window handles of all the windows and print them in a sequence.
  • 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.
 package selenium; 
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; 
//import org.openqa.selenium.support.ui.Select; 
public class selenium { public static void main(String[] args) throws Exception 
{ 
System.setProperty("webdriver.chrome.driver", "D:chromedriver.exe"); 
WebDriver driver = new ChromeDriver(); 
driver.get("https://www.edureka.co/"); 
String title = driver.getTitle(); System.out.println(title); 
//driver.get("http://www.google.co"); 
JavascriptExecutor js = (JavascriptExecutor) driver; 
driver.findElement(By.cssSelector("#search-inp")).sendKeys("Selenium Certification Course"); 
js.executeScript("window.scrollBy(0,40)"); 
driver.findElement(By.xpath("//span[@class='typeahead__button']")).click(); 
WebElement link = driver.findElement(By.xpath("//li[@class='ga-allcourses']//a[@class='giTrackElementHeader'][contains(text(),'Courses')]")); 
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("Best Training & Certification Courses for Professionals | Edureka")) 
{ 
System.out.println("a2"); 
js.executeScript("window.scrollBy(0,1000)"); 
System.out.println("b1"); 
driver.findElement(By.xpath("//*[@id="allc_catlist"]/li[3]/a")).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)"); 
} 
} 
} 

Now let’s check the output of the last program.


First, we’ll initialize the browser and get the URL of the web page we want to test and find the search box element on the page and send keys to the searchbox and click the search icon.


After this, we will open the course link in the new window using the action command


Once we do this, we’ll scroll down through the child window using the javascriptexecutor.


And after this, print the title of the first window and also the window handles of the two windows.

Now with this, we come to an end to this “How to handle multiple windows in Selenium” blog.

Find out our Selenium Training in Top Cities/Countries

IndiaOther Cities/Countries
BangaloreUS
HyderabadUK
PuneCanada
ChennaiAustralia
MumbaiSingapore
KolkataEdinburgh

I hope you guys enjoyed this article and understood what Selenium Webdriver is and how the window handle function helps switch between windows. Now that you understand how to work on multiple windows simultaneously, check out the Selenium Certification Course by Edureka, a trusted online learning company with a network of more than 650,000 satisfied learners spread across the globe. This course is designed to introduce you to the complete Selenium features and their importance in testing software. Got a question for us? Please mention it in the comments section of “How to handle multiple windows in Selenium,” and we will get back to you.

Upcoming Batches For Selenium Course
Course NameDateDetails
Selenium Course

Class Starts on 4th January,2025

4th January

SAT&SUN (Weekend Batch)
View Details
Selenium Course

Class Starts on 13th January,2025

13th January

MON-FRI (Weekday Batch)
View Details
BROWSE COURSES