Skip to content
CodeKruPro

Open a new tab and return to the original window

Automation taskMediumAsked in: Accenture, Capgemini, Cognizant, Infosys, TCS, Wipro

One of the most asked tasks: "Click a link that opens a new tab, check something there, close it and come back." Save the original handle before anything else, because you need it to return. In this lesson the new tab is opened with the Selenium 4 call (newWindow in Java, switch_to.new_window in Python) instead of a link click; you then read its title and switch back to the saved handle.

Handle Multiple Windows

Handle Multiple Windows

Selenium 4 provides driver.switchTo().newWindow(WindowType.TAB) to open a new tab.

Task:

  1. Navigate to https://testkru.com/Elements/TextFields
  2. Save the original window handle
  3. Open a new tab using Selenium 4's newWindow API
  4. Navigate the new tab to https://testkru.com/Elements/Buttons
  5. Print the new tab's title
  6. Switch back to the original window and print its title

Expected output:

Windows open: 2
New tab title: Buttons
Original title: Text Fields