Selenium 101: Managing Multiple Tabs
Test and Monitor | Posted April 02, 2018

As we’ve discovered through this Selenium 101 Series, automation can be challenging when your tests require more complex actions such as testing in two windows at once or closing a pop-up. Luckily, once you know the right commands, you can begin creating scripts that reach all parts of the application you need to check.

Just like you might open web pages in different tabs locally, it’s also possible to have multiple tabs up in one browser during a Selenium test. Multi-tab testing is a common annoyance for testers who are learning Selenium — how do you open more than one tab in a single browser window, then switch back and forth between them? Many pages do this on their own. For instance, any anchor tag with an attribute like target=”_blank” will open the link in a new tab. How do we handle this in our automated tests? The good news is that it’s not as hard as it seems.

With multi-tab testing, you might want to:

  • Launch your browser
  • Maximize your browser
  • Launch multiple tabs
  • Switch between the tabs
  • Perform actions on each tab
  • Close the browser

To first open a new tab (if one doesn’t open automatically when clicking a link), you’ll use driver.findElement(By.cssSelector(“body”)). followed by sendKeys(Keys.CONTROL+”t”); You can probably already tell that we’re focusing on our webpage, then sending ctrl + t to open a new tab the way you might normally in your browser.

Any time you switch between tabs, you’ll want to use the driver.switchTo().window(<some window>); method. This allows you to change control from one tab to another. The switchTo method is also how you handle alerts, so the steps will be very similar.

You might want to throw some waits in there for good measure, but it should look something like this:

WebDriver driver = new FirefoxDriver(); 

String newWindow = driver.getWindowHandle();

driver.get("Second URL");

//Perform whatever actions you want done on the secondary tab, let’s pretend we’re logging in somewhere



//Perform whatever actions you want done on the main tab, we’ll click a button

# Close current tab
driver.findElement(By.cssSelector(“body”)).sendKeys(Keys.CONTROL + 'w');


This script will give you a good foundation to use in future tests where you might want to switch tabs. For more in our Selenium 101 Series, check out our previous posts: