App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Get Started free
Home Guide How to handle Multiple Tabs in Selenium

How to handle Multiple Tabs in Selenium

By Neha Vaidya, Community Contributor -

As technology advances, it is necessary to adopt automation testing into the software 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 managing of multiple tabs on a browser. This article will discuss how to automate this action with Selenium so that the website’s behavior can be monitored by testers.

This article discusses the following scenarios:

  1. Switching between multiple tabs
  2. Opening a new tab using Selenium
  3. Closing the tab using Selenium

How to handle Multiple Tabs in Selenium

The user scenario being automated here is: Open a new tab and then switch back to the last tab to complete the other pending activities. To do so, use the Action Class approach or using Selenium WebDriver interface methods getWindowHandle & getWindowHandles. In such scenarios, Selenium helps handle multiple tabs through WindowHandlers.

Now let’s take an example scenario to understand how it works. The scenario here is as follows:

  1. Open the Amazon URL.
  2. Search for “Headphones” in the search bar.
  3. Save the URL of Headphones.
  4. Open a new tab.
  5. Switch to the new tab and launch the stored URL.

To open the URL, use the sendKeys command as shown below:

driver.findElement(By.cssSelector(“body”)).sendKeys(Keys.CONTROL+ “t”);

With this information, let’s understand how to handle multiple tabs using the WindowHandler Method.

Handling Multiple Tabs using Window Handler

The code below switches to the opened tab using the Window Handler methods:

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;

public class MultipleTabsExample{
public static void main(String[] args) throws InterruptedException, AWTException { System.setProperty("webdriver.chrome.driver", ".Path_to _Chrome_Driver");
WebDriver driver=new ChromeDriver();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
//Navigating to amazon.com
driver.get("https://www.amazon.in//");
driver.manage().window().maximize();
String currentHandle= driver.getWindowHandle();
// Searching for Headphones
driver.findElement(By.id("twotabsearchtextbox")).sendKeys("Headphones", Keys.ENTER);

//Clicking on search button
String UrlToClick=driver.findElement(By.xpath("//span[contains(text(),'Infinity (JBL) Glide 500 Wireless Headphones with ')]")).getAttribute("href");

Note: Below is the item to be clicked on to navigate to the new tab. The above Xpath is for the same one.

manage tabs in Selenium example

How to Open a New Tab in Selenium

To open the new tab, use the same robot class code as created above.

The only change here is that the code will click on the Returns and Orders link. In this case, the intent is to open one particular link (shown below) in a new tab as well as locate the link using Xpath.

open tabs in Selenium

//span[contains(text(),'& Orders')]
//Get all the handles currently available
Set<String> handles=driver.getWindowHandles();
for(String actual: handles) {
if(!actual.equalsIgnoreCase(currentHandle)) {
//Switch to the opened tab
driver.switchTo().window(actual); 
//opening the URL saved.
driver.get(urlToClick);
}
}
}
}
}

To switch back to the original tab, use the command below:

driver.navigate().to(“URL of the tab”);

In order to use Actions Class for the same example, simply do the following:

After using robot class for handling, the example above uses the WindowHandler Method. Replace that with the code snippet below to implement the Actions class.

//switch with the help of actions class 
Actions action = new Actions(driver); action.keyDown(Keys.CONTROL).sendKeys(Keys.TAB).build().perform(); //opening the URL saved. 
driver.get(urlToClick);

Now let’s understand how to close a tab using Selenium.

Run Selenium test for Free

How to Close Tab in Selenium

In the code below, first get all the window handles, then switch to the tab to be closed. After this, close the driver using driver.close().

browser.getAllWindowHandles().then(function (handles) { browser.driver.switchTo().window(handles[1]); 
browser.driver.close();
browser.driver.switchTo().window(handles[0]); 
}

On executing the code above, it will launch multiple tabs, and the window handle will be retrieved. Run the code, automate user navigation through multiple tabs, 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.

All Selenium tests must be run on real browsers and devices for accurate results. Start running tests on 2000+ real browsers and devices on BrowserStack’s real device cloud. Run parallel tests on its Cloud Selenium Grid to get faster results without compromising on accuracy. Detect the bugs and offer a high-end UX/UI to the users by automated testing in real user conditions with BrowserStack Automate.

Run Selenium Tests on Real Devices

Tags
Automation Testing Selenium Selenium Webdriver

Featured Articles

How to handle multiple windows in Selenium?

How to handle Alerts and Popups in Selenium?

App & Browser Testing Made Easy

Seamlessly test across 20,000+ real devices with BrowserStack