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<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
//Launch URL in the new tab
driver.get("http://google.com");


Kuldeep is the founder and lead author of ArtOfTesting. He is skilled in test automation, performance testing, big data, and CI-CD. He brings his decade of experience to his current role where he is dedicated to educating the QA professionals. You can connect with him on LinkedIn.
hi Kuldeep while I’m executing above code program working fine but it getting error
Exception in thread “main” java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at selflearingselenium.Browsercommods1.main(Browsercommods1.java:35)
//Switch focus to new tab
ArrayList tabs = new ArrayList (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
Hi Nikhil,
Are you sure, the point at which you are fetching the tabs, the new tab has opened?
It looks like there is only one tab currently that’s why you are getting indexOutOfBoundException. Maybe while debugging you can put a Thread.sleep() of 3 seconds.
I got the same exception, giving Thread.sleep(3000), helps, Thanks!
i still get error indexOutOfBoundException
But where have to give thread. Sleep(3000) before windowhandle or after
thank you