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
driver.get("http://www.google.com");
//Use robot class to press Ctrl+t keys
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_T);
//Switch focus to new tab
ArrayList tabs = new ArrayList (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
//Launch URL in the new tab
driver.get("http://google.com");