How to Handle Multiple Windows in Selenium?
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 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:
- What is Selenium Webdriver?
- How to run a test case in Selenium?
- Pre-requisites
- How to handle multiple windows?
- Syntax
- Demo
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?
- Selenium is an open source portable framework which helps in automating the testing of web applications.
- Test scripts in Selenium can be written in any programming language of your choice like Java, Python, C# and many more.
- Selenium has its own set of commands called Selenese, which holds the series of commands.
- It can run across various web browsers like Chrome, Safari, Firefox, IE and many more.
- Selenium Webdriver interacts directly with the browser rather than interacting with the server.
- It is fast and efficient.
- Selenium is highly flexible when it comes to functional testing and regression testing.
- Another interesting factor, Selenium makes use of element locators which help in finding the element on a web page. They are: class, name, XPath, ID, LinkText, DOM, Partial LinkText and CSS Selectors.
- It also uses plugins like Maven, JUnit to test the applications more fast and effectively.
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
- The first thing we require is to choose the right programming language to write the test scripts. As Java is one of the most simple and easy to understand language, we are going to add the JRE libraries to the project.
- We require an IDE where we can run the test scripts. There is NetBeans, Eclipse and many other IDEs but we prefer working on Eclipse IDE because it is highly effective while executing the Java projects.
- Some Selenium plugins like the Selenium standalone server, Selenium jar files, and Selenium IDE.
- Browser drivers for different browsers like Chrome, IE, Firefox, etc.
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,
- Initialize the web driver and create an object of the same.
- Instantiate the browser driver to the new ChromeDriver (in this case, we are working on ChromeDriver, you can choose Firefox or IE) and specify the path in which the ChromeDriver exists followed by the extension of an executable file.
- Get the URL of the particular web page which you want to test
- Find the element using one of the element locators in Selenium
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.
How to Handle Multiple Windows?
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.
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
- get.windowhandle(): helps in getting the window handle of the current window
- get.windowhandles(): helps in getting the handles of all the windows opened
- set: helps to set the window handles which is in the form of a string. set<string> set= driver.get.windowhandles()
- switch to: helps in switching between the windows
- action: helps to perform certain actions on the windows.
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.
Demo
In this demo section, we’ll automate a few websites and check how to handle multiple windows.
We’ll automate pages such as,
- ToolsQA website for testing the window handle function
- We’ll also automate our official website edureka.co and perform some actions
- Naukri.com which is one of the most popular online job portals
Now, we’ll first start by testing the webpage ToolsQA
- We will first specify the browser driver on which we are going to work and specify the path in which it is located using this command: System.setProperty(“webdriver.chrome.driver”, “D:\\\\chromedriver.exe”);
- Instantiate the web driver to the new chrome driver.
- Get the URL of the web page that we want to test.
- Inspect the element and find it on the webpage using the element locators, in this case, it is the ID.
- After this, we need to open multiple child windows. So, I’m going to do this using the for loop.
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 search box 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.
If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.
Do look out for other articles in this series which will explain the various other aspects of Selenium.
2. Selenium WebDriver: TestNG For Test Case Management & Report Generation
3. Building A Data Driven, Keyword Driven & Hybrid Selenium Framework
7. Setting up a Selenium Grid for distributed Selenium testing
9. Cross Browser Testing Using LambdaTest
10. Cross Browser Testing Using Selenium
11. Page Object Model In Selenium
13. QTP vs Selenium
14. Selenium vs RPA
15. Selenium WebDriver Architecture
Originally published at https://www.edureka.co on April 16, 2019.