New Tab in Selenium 4

switchTo().newWindow

Selenium 4 can open a new tab or window itself and switches to it automatically:

import org.openqa.selenium.WindowType;

driver.get("https://shopease.example.com/products/101");
driver.switchTo().newWindow(WindowType.TAB);          // new empty tab, already focused
driver.get("https://shopease.example.com/products/205");
String second = driver.findElement(By.cssSelector(".price")).getText();

driver.switchTo().newWindow(WindowType.WINDOW);       // a separate browser window
System.out.println("Windows open: " + driver.getWindowHandles().size());

Example

Output:

Run CompareProductsTest.main()

Example output

Windows open: 3

When to Use It

  • Compare two products or two user views side by side in one test.
  • Open the admin panel in a second tab to approve an order created in the first tab.

Note: Tabs share cookies, so both tabs are logged in as the same user. For two different users (buyer and admin), start two separate WebDriver instances.