[selenium] How to open a new tab using Selenium WebDriver

How can I open a new tab in the existing Firefox browser using Selenium WebDriver (a.k.a. Selenium 2)?

This question is related to selenium firefox selenium-webdriver browser-tab

The answer is


I had trouble opening a new tab in Google Chrome for a while.

Even driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t"); didn't work for me.

I found out that it's not enough that Selenium has focus on driver. Windows also has to have the window in the front.

My solution was to invoke an alert in Chrome that would bring the window to front and then execute the command. Sample code:

((JavascriptExecutor)driver).executeScript("alert('Test')");
driver.switchTo().alert().accept();
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");

 Actions at=new Actions(wd);
 at.moveToElement(we);
 at.contextClick(we).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());

driver.switchTo().window(tabs.get(0));

Java

I recommend using JavascriptExecutor:

  • Open new blank window:
((JavascriptExecutor) driver).executeScript("window.open()");
  • Open new window with specific URL:
((JavascriptExecutor) driver).executeScript("window.open('https://google.com')");

Following import:

import org.openqa.selenium.JavascriptExecutor;

Selenium doesn't support opening new tabs. It only supports opening new windows. For all intents and purposes a new window is functionally equivalent to a new tab anyway.

There are various hacks to work around the issue, but they are going to cause you other problems in the long run.


Almost all answers here are out of date.

(Ruby examples)

WebDriver now has support for opening tabs:

browser = Selenium::WebDriver.for :chrome
new_tab = browser.manage.new_window

Will open a new tab. Opening a window has actually become the non-standard case:

browser.manage.new_window(:window)

The tab or window will not automatically be focussed. To switch to it:

browser.switch_to.window new_tab

Due to a bug in https://bugs.chromium.org/p/chromedriver/issues/detail?id=1465 even though webdriver.switchTo actually does switch tabs, the focus is left on the first tab.

You can confirm this by doing a driver.get after the switchWindow and see that the second tab actually go to the new URL and not the original tab.

A workaround for now is what yardening2 suggested. Use JavaScript code to open an alert and then use webdriver to accept it.


To open new tab using JavascriptExecutor,

((JavascriptExecutor) driver).executeScript("window.open()");
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));

Will control on tab as according to index:

driver.switchTo().window(tabs.get(1));

Driver control on main tab:

driver.switchTo().window(tabs.get(0));

Question: How can I open a new tab using Selenium WebDriver with Java?

Answer: After a click on any link, open a new tab.

If we want to handle a newly open tab then we have need to handle tab using the .switchTo().window() command.

Switch to a particular tab, and then perform an operation and switch back to into the parent tab.

package test;

import java.util.ArrayList;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Tab_Handle {

    public static void main(String[] args) {

        System.setProperty("webdriver.gecko.driver", "geckodriver_path");

        WebDriver driver = new FirefoxDriver();

        driver.get("http://www.google.com");

        // Store all currently open tabs in Available_tabs
        ArrayList<String> Available_tabs = new ArrayList<String>(driver.getWindowHandles());

        // Click on link to open in new tab
        driver.findElement(By.id("Url_Link")).click();

        // Switch newly open Tab
        driver.switchTo().window(Available_tabs.get(1));

        // Perform some operation on Newly open tab
        // Close newly open tab after performing some operations.
        driver.close();

        // Switch to old(Parent) tab.
        driver.switchTo().window(Available_tabs.get(0));

    }

}

The below code will open the link in a new window:

String selectAll = Keys.chord(Keys.SHIFT, Keys.RETURN);
driver.findElement(By.linkText("linkname")).sendKeys(selectAll);

// To open a new tab in an existing window
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +  "t");

To open a new tab in the existing Firefox browser using Selenium WebDriver

FirefoxDriver driver = new FirefoxDriver();
driver.findElement(By.tagName("body")).sendKeys(Keys.CONTROL,"t"); 

This line of code will open a new browser tab using Selenium WebDriver:

((JavascriptExecutor)getDriver()).executeScript("window.open()");

How can we open a new, but more importantly, how do we do stuff in that new tab?

Webdriver doesn't add a new WindowHandle for each tab, and only has control of the first tab. So, after selecting a new tab (Control + Tab Number) set .DefaultContent() on the driver to define the visible tab as the one you're going to do work on.

Visual Basic

Dim driver = New WebDriver("Firefox", BaseUrl)

' Open new tab - send Control T
Dim body As IWebElement = driver.FindElement(By.TagName("body"))
body.SendKeys(Keys.Control + "t")

' Go to a URL in that tab
driver.GoToUrl("YourURL")


' Assuming you have m tabs open, go to tab n by sending Control + n
body.SendKeys(Keys.Control + n.ToString())

' Now set the visible tab as the drivers default content.
driver.SwitchTo().DefaultContent()

Try this for the Firefox browser.

/*  Open new tab in browser */
public void openNewTab()
{
    driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
    ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
    driver.switchTo().window(tabs.get(0));
}

Check this complete example to understand how to open multiple tabs and switch between the tabs and at the end close all tabs.

public class Tabs {

    WebDriver driver;

    Robot rb;

    @BeforeTest
    public void setup() throws Exception {
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Anuja.AnujaPC\\Downloads\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        driver.get("http://qaautomated.com");
    }

    @Test
    public void openTab() {
        // Open tab 2 using CTRL + T keys.
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

        // Open URL In 2nd tab.
        driver.get("http://www.qaautomated.com/p/contact.html");

        // Call switchToTab() method to switch to the first tab
        switchToTab();

        // Call switchToTab() method to switch to the second tab.
        switchToTab();
    }

    public void switchToTab() {
        // Switching between tabs using CTRL + tab keys.
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");

        // Switch to current selected tab's content.
        driver.switchTo().defaultContent();
    }

    @AfterTest
    public void closeTabs() throws AWTException {
        // Used Robot class to perform ALT + SPACE + 'c' keypress event.
        rb = new Robot();
        rb.keyPress(KeyEvent.VK_ALT);
        rb.keyPress(KeyEvent.VK_SPACE);
        rb.keyPress(KeyEvent.VK_C);
    }

}

This example is given by this web page.


This code is working for me (Selenium 3.8.1, chromedriver 2.34.522940, and Chrome 63.0):

public void openNewTabInChrome() {

    driver.get("http://www.google.com");

    WebElement element = driver.findElement(By.linkText("Gmail"));
    Actions actionOpenLinkInNewTab = new Actions(driver);
    actionOpenLinkInNewTab.moveToElement(element)
            .keyDown(Keys.CONTROL) // MacOS: Keys.COMMAND
            .keyDown(Keys.SHIFT).click(element)
            .keyUp(Keys.CONTROL).keyUp(Keys.SHIFT).perform();


    ArrayList<String> tabs = new ArrayList(driver.getWindowHandles());
    driver.switchTo().window(tabs.get(1));
    driver.get("http://www.yahoo.com");
    //driver.close();
}

Just for anyone else who's looking for an answer in Ruby, Python, and C# bindings (Selenium 2.33.0).

Note that the actual keys to send depend on your OS. For example, Mac uses CMD + T, instead of Ctrl + T.

Ruby

require 'selenium-webdriver'

driver = Selenium::WebDriver.for :firefox
driver.get('http://stackoverflow.com/')

body = driver.find_element(:tag_name => 'body')
body.send_keys(:control, 't')

driver.quit

Python

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/")

body = driver.find_element_by_tag_name("body")
body.send_keys(Keys.CONTROL + 't')

driver.close()

C#

using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace StackOverflowTests {

    class OpenNewTab {

        static void Main(string[] args) {

            IWebDriver driver = new FirefoxDriver();
            driver.Navigate().GoToUrl("http://stackoverflow.com/");

            IWebElement body = driver.FindElement(By.TagName("body"));
            body.SendKeys(Keys.Control + 't');

            driver.Quit();
        }
    }
}

The same example for Node.js:

var webdriver = require('selenium-webdriver');
...
driver = new webdriver.Builder().
                    withCapabilities(capabilities).
                    build();
...
driver.findElement(webdriver.By.tagName("body")).sendKeys(webdriver.Key.COMMAND + "t");

If you want to open the new tab you can use this

 ((JavascriptExecutor) getDriver()).executeScript("window.open()");

If you want to open the link from the new tab you can use this

With JavascriptExecutor:

 public void openFromNewTab(WebElement element){
            ((JavascriptExecutor)getDriver()).executeScript("window.open('"+element.getAttribute("href")+"','_blank');");
        }

With Actions:

 WebElement element = driver.findElement(By.xpath("your_xpath"));
 Actions actions = new Actions(driver);
        actions.keyDown(Keys.LEFT_CONTROL)
                .click(element)
                .keyUp(Keys.LEFT_CONTROL)
                .build()
                .perform();

Handling a browser window using Selenium WebDriver:

String winHandleBefore = driver.getWindowHandle();

for(String winHandle : driver.getWindowHandles())  // Switch to new opened window
{
    driver.switchTo().window(winHandle);
}

driver.switchTo().window(winHandleBefore);   // Move to previously opened window

How to open a new tab using Selenium WebDriver with Java for Chrome:

ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-extensions");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.navigate().to("https://google.com");
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_T);

The above code will disable first extensions and using the robot class, a new tab will open.


You can use the following code using Java with Selenium WebDriver:

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");

By using JavaScript:

WebDriver driver = new FirefoxDriver(); // Firefox or any other Driver
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.open()");

After opening a new tab it needs to switch to that tab:

ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));

To open a new tab in the existing Chrome browser using Selenium WebDriver you can use this code:

driver.FindElement(By.CssSelector("body")).SendKeys(Keys.Control + "t");        
string newTabInstance = driver.WindowHandles[driver.WindowHandles.Count-1].ToString();
driver.SwitchTo().Window(newTabInstance);
driver.Navigate().GoToUrl(url);

To open a new window in Chrome Driver.

// The script that will will open a new blank window
// If you want to open a link new tab, replace 'about:blank' with a link
String a = "window.open('about:blank','_blank');";
((JavascriptExecutor)driver).executeScript(a);

For switching between tabs, read here.


I am using Selenium 2.52.0 in Java and Firefox 44.0.2. Unfortunately none of the previous solutions worked for me.

The problem is if I a call driver.getWindowHandles() I always get one single handle. Somehow this makes sense to me as Firefox is a single process and each tab is not a separate process. But maybe I am wrong. Anyhow, I try to write my own solution:

// Open a new tab
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");

// URL to open in a new tab
String urlToOpen = "https://url_to_open_in_a_new_tab";

Iterator<String> windowIterator = driver.getWindowHandles()
        .iterator();
// I always get handlesSize == 1, regardless how many tabs I have
int handlesSize = driver.getWindowHandles().size();

// I had to grab the original handle
String originalHandle = driver.getWindowHandle();

driver.navigate().to(urlToOpen);

Actions action = new Actions(driver);
// Close the newly opened tab
action.keyDown(Keys.CONTROL).sendKeys("w").perform();
// Switch back to original
action.keyDown(Keys.CONTROL).sendKeys("1").perform();

// And switch back to the original handle. I am not sure why, but
// it just did not work without this, like it has lost the focus
driver.switchTo().window(originalHandle);

I used the Ctrl + T combination to open a new tab, Ctrl + W to close it, and to switch back to original tab I used Ctrl + 1 (the first tab).

I am aware that mine solution is not perfect or even good and I would also like to switch with driver's switchTo call, but as I wrote it was not possible as I had only one handle. Maybe this will be helpful to someone with the same situation.


Do this:

driver.ExecuteScript("window.open('your URL', '_blank');");

Examples related to selenium

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Class has been compiled by a more recent version of the Java Environment How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? element not interactable exception in selenium web automation Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception?

Examples related to firefox

Drag and drop menuitems Class has been compiled by a more recent version of the Java Environment Only on Firefox "Loading failed for the <script> with source" Selenium using Python - Geckodriver executable needs to be in PATH Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property How to use the gecko executable with Selenium Selenium 2.53 not working on Firefox 47 Postman addon's like in firefox Edit and replay XHR chrome/firefox etc? How to enable CORS on Firefox?

Examples related to selenium-webdriver

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? Scrolling to element using webdriver? Only local connections are allowed Chrome and Selenium webdriver Check if element is clickable in Selenium Java

Examples related to browser-tab

How to open a link in new tab (chrome) using Selenium WebDriver? How to open link in new tab on html? How to open a new tab using Selenium WebDriver How can I get the URL of the current tab from a Google Chrome extension?