Useful Methods for Working with Multiple Tabs

  • driver.getWindowHandle(); - returns the current window handle (tab) with which the driver is working. Technical return type is a String. Hint: use this method to capture your current "main" tab before opening links or working with a second tab.
  • driver.getWindowHandles() - returns a Set of all currently open window tabs:
  • driver.getWindowHandles().size() is "How many tabs do I have open in this driver?"
  • `driver.close()` - when switched to a new tab with which you're done (typical workflow: click link to open in new tab, verify that link/tab opened successfully, and now you're done with that link/tab"), use this to close the new tab.

Sample Codeblock

Copied from https://stackoverflow.com/questions/9588827/how-to-switch-to-the-new-browser-window-which-opens-after-click-on-the-button:

// Store the current window handle
String winHandleBefore = driver.getWindowHandle();

// Perform the click operation that opens new window

// Switch to new window opened
for(String winHandle : driver.getWindowHandles()){
    driver.switchTo().window(winHandle);
}

// Perform the actions on new window

// Close the new window, if that window no more required
driver.close();

// Switch back to original browser (first window)
driver.switchTo().window(winHandleBefore);

// Continue with original browser (first window)

-- StanVogel - 14 Apr 2020
Topic revision: r1 - 14 Apr 2020, StanVogel
© 2020 Ultranauts - 75 Broad Street, 2nd Floor, Suite 206, New York, NY 10004 - info@ultranauts.co