Selenium WebDriver is a popular tool for automating web testing with many functionalities. One of the common actions when automating the web is to open a new tab in the browser window.
Opening a new tab can be useful in various scenarios, including testing multi-page workflows, verifying external links that open in a new tab, interacting with pop-up windows, and simulating multiple users interacting with different parts of the application simultaneously when running tests in parallel.
Earlier solutions were custom scripts like sending a combination of keys, such as “Ctrl” + “T,” which usually led to different results depending on the browser and operating system.
2. Using the newWindow() API
Selenium 4 introduced a powerful and flexible API method newWindow(), for creating a new window in the current browser session. It allows us to open a new browser tab and switch to it automatically. This method takes a WindowType parameter WINDOW or TAB and creates it. The syntax is pretty straightforward:
Here’s how to use this approach to open a new tab:
And the how to open a new tab with URL:
It’s important to keep in mind that the driver will still be focused on the original tab after the window.open() method is executed. In order to interact with elements on the new tab, we need to switch the driver’s focus to that tab using the driver.switchTo().window() method.
String newTab = driver.getWindowHandles() .stream() .filter(handle -> !handle.equals(originalTab)) .findFirst() .get(); driver.switchTo().window(newTab);
As always, the code examples are available on GitHub.