How to Open New Tab, Close Tab, and handle Multiple Tabs in Selenium

Learn to open, close, switch between tabs, and handle multiple tabs in Selenium.

Get Started free
How-to-handle-Multiple-Tabs-in-Selenium
Home Guide How to Open New Tab, Close Tab, and handle Multiple Tabs in Selenium

How to Open New Tab, Close Tab, and handle Multiple Tabs in Selenium

Handling multiple tabs is a critical aspect of browser automation in Selenium. Tasks like opening a new tab, switching between tabs, and closing tabs can be performed efficiently using Selenium’s features, such as opening tabs and window handles for managing them.

By automating these actions, testers can ensure that the website behaves as expected when users open, switch, or close tabs.

This article explores how to automate switching between tabs, opening new tabs, and closing tabs using Selenium to enhance test coverage and improve user experience.

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

When to Open a New Tab in Selenium

Opening new tabs during Selenium automation testing can help organize and streamline the testing process. Here are key scenarios where opening a new tab is beneficial:

  • Data Extraction: When scraping information from a website, new tabs can be opened to handle data from multiple sources or products simultaneously, improving efficiency without interrupting the main testing flow.
  • Cross-Platform Testing: For testing website behavior across different devices or browsers, opening new tabs allows testers to execute tests in parallel on multiple platforms without interfering with each other.
  • Simulating User Workflow: Opening new tabs is useful when testing a user’s journey, which requires interacting with multiple web pages, such as checking product details while making a purchase or comparing prices.

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.

When to Close a Tab in Selenium

Closing unnecessary tabs during Selenium automation can enhance testing efficiency and conserve resources. Here are a few scenarios where closing tabs is essential:

  • E-commerce Testing: When gathering data from multiple products on an e-commerce site, tabs are often opened for each product. Once the required information is extracted, closing the tabs helps free up system resources and speeds up subsequent tests.
  • Multimedia Uploading Tests: In platforms like YouTube, multiple parallel uploads can be tested across various tabs, browsers, or systems, and many tabs can be opened. Closing these tabs after each upload test ensures that memory and processing power are available for further tests.
  • Parallel Testing: During parallel testing, where multiple features are tested on different tabs and browsers, numerous open tabs can complicate error troubleshooting. Closing tabs regularly allows for a more precise and manageable testing environment.

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

BrowserStack Automate Banner

Switching Windows or Tabs in Selenium

When clicking a link that opens a new window or tab, the new window will become the focus on the screen. However, Selenium WebDriver doesn’t automatically know which window the operating system considers active. Therefore, to interact with the new window or tab, you’ll need to switch to it.

Steps to Switch Windows or Tabs:

  1. Fetch Window Handles: Selenium provides window handles for all open windows or tabs.
  2. Store Handles in an Array: The window handles are stored in an array in the order in which the windows or tabs were opened. The first position typically represents the default browser window, followed by any new windows or tabs.
  3. Switch to the Desired Window/Tab: To interact with a specific window or tab, switch to it using the appropriate window handle.

This process ensures that you can perform actions in the correct window or tab, even when multiple windows are open simultaneously.

Talk to an Expert

Conclusion

All Selenium tests must be run on real browsers and devices for accurate results. Start running tests on 3500+ 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.

Tags
Automation Testing Selenium Selenium Webdriver