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 sendKeys method to any element. But Action class and sendKeys method doesn't work with some browser/drivers versions. So, in this post we will see how to use Robot class to open a new tab as it is mpst 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 keyboard event of pressing Control Key followed by 't' key of 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<String> tabs = new ArrayList<String> (driver.getWindowHandles());

//Launch URL in the new tab