eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

1. Overview

In this tutorial, we’ll look at how we can handle browser tabs with Selenium. There are cases when clicking on a link or button will open the page in a new tab. In these cases, we must handle the tabs properly to continue with our tests. This tutorial covers opening pages in new tabs, switching between tabs, and closing tabs. For our examples, we’ll use https://testpages.herokuapp.com.

2. Setup

Based on the WebDriver setup, we’ll create a SeleniumTestBase class that takes care of the WebDriver setup and teardown. Our test classes will extend this class. We’ll also define a helper class for tab handling with Selenium. This helper class will contain methods for opening, switching, and closing tabs. These methods will be shown and explained in the following sections. We’ll initialize an instance of that helper class in the SeleniumTestBase. All examples use JUnit5.

The initialization is done in the init() method, which needs to be annotated with @BeforeAll:

@BeforeAll
public static void init() {
    setupChromeDriver();
}

The teardown or cleanup method will close the entire browser after all tests:

@AfterAll
public static void cleanup() {
    if (driver != null) {
        driver.quit();
    }
}

3. Basics

A typical case where we need to handle tabs is when a new tab is opened when clicking on a link or button. Links on a website with the target attribute set to _blank will be opened in a new tab, e.g.:

<a href="/" >Baeldung.com</a>

Such a link opens the target in a new tab, e.g., https://www.baeldung.com.

3.2. Window Handle

In Selenium, each tab has a window handle which is a unique string. For Chrome tabs, the string starts with CDwindow, followed by 32 hex characters, e.g., CDwindow-CDE9BEF919431FDAA0FC9CB7EBBD4E1A. We need the window handle when switching to a specific tab. Therefore, we need to store the window handles during our tests.

4. Tab Handling

4.1. Open Tab

With Selenium >= 4.0, it is possible to open a new tab without using Javascript or browser hotkeys. The WebDriver provides the following method to open a new tab:

driver.switchTo().newWindow(WindowType.TAB);

As mentioned in the previous section, there are links with the target attribute set. In these cases, we don’t need to open the tab ourselves, but we need to take care of switching to and closing them. Although such a link opens the page in a new tab, it doesn’t switch to the new tab. We need to take care of that ourselves. One approach is to compare the window handles before clicking the link with the window handles after clicking the link. There should be one new window handle that represents the newly opened tab.

We can retrieve the set of window handles and the window handle of the active tab with the following methods of the WebDriver:

driver.getWindowHandles();
driver.getWindowHandle()

With the help of these methods, we can implement a helper method in the TabHelper class. It opens a link in a new tab and switches to that tab. The tab switch will only be performed if a new tab has been opened.

String openLinkAndSwitchToNewTab(By link) {
    String windowHandle = driver.getWindowHandle();
    Set<String> windowHandlesBefore = driver.getWindowHandles();

    driver.findElement(link).click();
    Set<String> windowHandlesAfter = driver.getWindowHandles();
    windowHandlesAfter.removeAll(windowHandlesBefore);

    Optional<String> newWindowHandle = windowHandlesAfter.stream().findFirst();
    newWindowHandle.ifPresent(s -> driver.switchTo().window(s));

    return windowHandle;
}

Finding the window handle is done by retrieving the window handles before and after the click on the link. The set of window handles before the click will be removed from the set of window handles after the click. The result will be the window handle of the new tab or an empty set. The method also returns the window handle of the tab before the switch.

4.2. Switch Tabs

Whenever we have multiple tabs open, we need to switch between them manually. We can switch to a specific tab with the following statement where destinationWindowHandle represents the window handle of the tab we want to switch to:

driver.switchTo().window(destinationWindowHandle)

A helper method can be implemented that takes the destination window handle as an argument and switches to the respective tab. Additionally, the method returns the window handle of the active tab before switching:

public String switchToTab(String destinationWindowHandle) {
    String currentWindowHandle = driver.getWindowHandle();
    driver.switchTo().window(destinationWindowHandle);
    return currentWindowHandle;
}

4.3. Close Tabs

After our tests or whenever we don’t need a specific tab anymore, we need to close it. Selenium provides a statement to close the current tab or the entire browser if it is the last open tab:

driver.close();

We can use this statement to close all tabs we don’t need anymore. With the following method, we can close all tabs except a specific tab:

void closeAllTabsExcept(String windowHandle) {
    for (String handle : driver.getWindowHandles()) {
        if (!handle.equals(windowHandle)) {
            driver.switchTo().window(handle);
            driver.close();
        }
    }
    driver.switchTo().window(windowHandle);
}

In this method, we loop through all window handles. If the window handle is different from the provided window handle, we’ll switch to it and close it. In the end, we’ll make sure to switch again to our desired tab.

We can use this method to close all tabs except the currently open tab:

void closeAllTabsExceptCurrent() {
    String currentWindow = driver.getWindowHandle();
    closeAllTabsExcept(currentWindow);
}

We can now use this method in our SeleniumTestBase class after each test to close all remaining tabs. This is especially useful in case a test fails to clean up the browser before starting the next test not to influence the results. We’ll call the method in a with @AfterEach annotated method:

@AfterEach
public void closeTabs() {
    tabHelper.closeAllTabsExceptCurrent();
}

4.4. Handle Tabs with Hot Keys

With Selenium, it was possible to handle tabs with browser hotkeys. Unfortunately, this seems not to work anymore because of changes to the ChromeDriver.

5. Tests

We can verify that the tab handling with our TabHelper class works as intended with a few simple tests. As mentioned in the introduction of this article, our test class needs to extend SeleniumTestBase:

class SeleniumTabsLiveTest extends SeleniumTestBase {
    //...
}

For these tests, we are declaring a few constants for URLs and locators in our test class, as shown below:

By LINK_TO_ATTRIBUTES_PAGE_XPATH = By.xpath("//a[.='Attributes in new page']");
By LINK_TO_ALERT_PAGE_XPATH = By.xpath("//a[.='Alerts In A New Window From JavaScript']");

String MAIN_PAGE_URL = "https://testpages.herokuapp.com/styled/windows-test.html";
String ATTRIBUTES_PAGE_URL = "https://testpages.herokuapp.com/styled/attributes-test.html";
String ALERT_PAGE_URL = "https://testpages.herokuapp.com/styled/alerts/alert-test.html";

In our first test case, we are opening a link in a new tab. We are verifying that we have two tabs open and can switch between them. Note that we always store the respective window handle. The following code represents this test case:

void givenOneTab_whenOpenTab_thenTwoTabsOpen() {
    driver.get(MAIN_PAGE_URL);

    String mainWindow = tabHelper.openLinkAndSwitchToNewTab(LINK_TO_ATTRIBUTES_PAGE_XPATH);
    assertEquals(ATTRIBUTES_PAGE_URL, driver.getCurrentUrl());

    tabHelper.switchToTab(mainWindow);
    assertEquals(MAIN_PAGE_URL, driver.getCurrentUrl());
    assertEquals(2, driver.getWindowHandles().size());
}

In our second test, we want to verify that we can close all tabs except our first open tab. We need to provide the window handle of that tab. The following code shows this test case:

void givenTwoTabs_whenCloseAllExceptMainTab_thenOneTabOpen() {
    driver.get(MAIN_PAGE_URL);
    String mainWindow = tabHelper.openLinkAndSwitchToNewTab(LINK_TO_ATTRIBUTES_PAGE_XPATH);
    assertEquals(ATTRIBUTES_PAGE_URL, driver.getCurrentUrl());
    assertEquals(2, driver.getWindowHandles().size());

    tabHelper.closeAllTabsExcept(mainWindow);

    assertEquals(1, driver.getWindowHandles().size());
    assertEquals(MAIN_PAGE_URL, driver.getCurrentUrl());
}

6. Conclusion

In this article, we learned how we handle browser tabs with Selenium. We covered how we can distinguish different tabs with their respective window handles. Opening tabs, switching tabs, and closing them when we are finished are covered in this article.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)