Open new tab in Selenium

Open a New Tab in Selenium

Last updated on

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<String> tabs = new ArrayList<String> (driver.getWindowHandles());
//Launch URL in the new tab

7 thoughts on “Open a New Tab in Selenium”

  1. 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(

    //Switch focus to new tab
    ArrayList tabs = new ArrayList (driver.getWindowHandles());

    • 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.

  2. I want to nagivate and click on the whatsapp tab for that i am proving xpath in pom class and write the script
    public void navigatewhatsappicon() {
    Assert.assertTrue(whatsappicon.isDisplayed(), “WhatsApp icon not displayed”);;

    public void navigateFacebookicon() {
    Assert.assertTrue(Facebookicon.isDisplayed(), “Facebookicon icon not displayed”);;

    public void navigateLinkdeinicon() {
    Assert.assertTrue(Linkedinicon.isDisplayed(), “Linkedeinicon icon not displayed”);;

    but it is not clicking the whatsapp tab need to add something


Leave a Comment