Open a New Tab in Selenium

Open a New Tab in Selenium

In this tutorial, we will learn how to open a new tab in Selenium Webdriver with Java. Although there are multiple ways of opening a new tab in Selenium like using Robot class, using Actions class, passing Keys.Control+”t” in the sendKeys() method to any element.

But Action class and sendKeys method doesn’t work with some browser/driver versions. So, in this post, we will see how to use the Robot class to open a new tab as it is the most stable option to perform this action.

Robot Class to Open Tab

As we know that Robot class in Selenium is used for simulating keyboard and mouse events. So, in order to open a new tab, we can simulate the keyboard event of pressing Control Key followed by ‘t’ key of the keyboard. After the new tab gets opened, we need to switch focus to it otherwise the driver will try to perform the operation on the parent tab only.
For switching focus, we will be using getWindowHandles() to get the handle of the new tab and then switch focus to it.

//Launch the first URL
//Use robot class to press Ctrl+t keys
Robot robot = new Robot();
//Switch focus to new tab
ArrayList tabs = new ArrayList (driver.getWindowHandles());
//Launch URL in the new tab

От QA genius