0
0
Selenium Javatesting~5 mins

Creating new windows/tabs in Selenium Java

Choose your learning style9 modes available
Introduction

Sometimes, you need to open a new browser window or tab to test how your web app behaves with multiple pages open.

Testing login flows that open a new tab for authentication.
Checking if links open correctly in new windows or tabs.
Verifying pop-up windows or help pages open as expected.
Testing multi-step processes that require switching between tabs.
Validating that session data persists across multiple windows.
Syntax
Selenium Java
driver.switchTo().newWindow(WindowType.TAB);
driver.switchTo().newWindow(WindowType.WINDOW);

Use WindowType.TAB to open a new tab.

Use WindowType.WINDOW to open a new browser window.

Examples
This example opens a new tab and navigates to Google.
Selenium Java
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
// Open new tab
WebDriver newTab = driver.switchTo().newWindow(WindowType.TAB);
newTab.get("https://google.com");
This example opens a new browser window and navigates to Bing.
Selenium Java
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
// Open new window
WebDriver newWindow = driver.switchTo().newWindow(WindowType.WINDOW);
newWindow.get("https://bing.com");
Sample Program

This test opens a new tab, navigates to Google, verifies the page title, then switches back to the original window.

Selenium Java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WindowType;
import org.openqa.selenium.chrome.ChromeDriver;

public class NewWindowTabTest {
    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        try {
            driver.get("https://example.com");
            String originalHandle = driver.getWindowHandle();

            // Open new tab
            WebDriver newTab = driver.switchTo().newWindow(WindowType.TAB);
            newTab.get("https://google.com");

            // Check title contains 'Google'
            if (newTab.getTitle().contains("Google")) {
                System.out.println("New tab opened successfully with Google.");
            } else {
                System.out.println("Failed to open Google in new tab.");
            }

            // Switch back to original window
            driver.switchTo().window(originalHandle);
            System.out.println("Back to original window with title: " + driver.getTitle());

        } finally {
            driver.quit();
        }
    }
}
OutputSuccess
Important Notes

Always store the original window handle before opening new windows or tabs to switch back later.

Use driver.quit() to close all browser windows after the test.

Opening new windows or tabs requires Selenium 4 or higher.

Summary

Use driver.switchTo().newWindow(WindowType.TAB) to open a new tab.

Use driver.switchTo().newWindow(WindowType.WINDOW) to open a new window.

Remember to switch between windows or tabs using window handles.