[java] How to open a link in new tab (chrome) using Selenium WebDriver?

System.setProperty("webdriver.chrome.driver", "D:\\softwares\\chromedriver_win32\\chromedriver.exe");

WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://mail.google.com/");
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN); 
driver.findElement(By.linkText("www.facebook.com")).sendKeys(selectLinkOpeninNewTab);

New tab is opening but URL link is not opening.

The answer is


Selenium can only automate on the WebElements of the browser. Opening a new tab is an operation performed on the webBrowser which is a stand alone application. For doing this you can make use of the Robot class from the java.util.* package which can perform operations using the keyboard regardless of what type of application it is. So here's the code for your operation. Note that you cannot automate stand alone applications using the Robot class but you can perform keyboard or mouse operations

System.setProperty("webdriver.chrome.driver","softwares\\chromedriver_win32\\chromedriver.exe"); 
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://www.google.com");
Robot rob = new Robot();
rob.keyPress(keyEvent.VK_CONTROL);
rob.keyPress(keyEvent.VK_T);
rob.keyRelease(keyEvent.VK_CONTROL);
rob.keyRelease(keyEvent.VK_T);

After this step you will need a window iterator to switch to the new tab:

Set <String> ids = driver.getWindowHandles();
Iterator <String> it = ids.iterator();
String currentWindow = it.next();
String newWindow = it.next();
driver.switchTo().window(newWindow);
driver.findElement(By.linkText("www.facebook.com")).sendKeys(selectLinkOpeninNewTab);

To switch between tabs action class does not always works on all browser and on all webdriver. the best way is to use robot class. try this code.

        String website = "https://www.google.com";
        String website1 = "https://www.msn.com/en-in/";
        String controlpath = "C:\\Libraries\\msedgedriver.exe";
        System.setProperty("webdriver.edge.driver", controlpath);
        driver = new EdgeDriver();
        driver.manage().window().maximize(); //  Maximize browser
        driver.get(website);
        System.out.println("Google page");
        
        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());
        //System.out.println("Handle info"+ driver.getWindowHandles());
        driver.switchTo().window(tabs.get(1));
    
        //Launch URL in the new tab
        driver.get(website1);
        System.out.println("msn page");
        Thread.sleep(5000);
        driver.switchTo().window(tabs.get(0));
        Thread.sleep(5000);

for clicking on the link which expected to be opened from new tab use this

WebDriver driver = new ChromeDriver(); 
driver.get("https://www.yourSite.com"); 
WebElement link=driver.findElement(By.xpath("path_to_link")); 

Actions actions = new Actions(driver); 
actions.keyDown(Keys.LEFT_CONTROL) 
       .click(element) 
       .keyUp(Keys.LEFT_CONTROL) 
       .build() 
       .perform(); 

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

There are multiple ways to open a link in new tab in using Selenium WebDriver.


Usecase A: Opening an adjacent blank tab and iterating through an iterator

  • Code Block:

    import java.util.Iterator;
    import java.util.Set;
    
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    
    public class NewTab_blank_iterator {
    
        public static void main(String[] args) {
    
            System.setProperty("webdriver.chrome.driver","C:\\WebDrivers\\chromedriver.exe");
            ChromeOptions options = new ChromeOptions();
            options.addArguments("start-maximized");
            WebDriver driver =  new ChromeDriver(options); 
            driver.get("https://mail.google.com/");
            String firstWindowHandle = driver.getWindowHandle();
            System.out.println("First Window Handle is: "+firstWindowHandle);
            // Opening an adjacent blank tab
            ((JavascriptExecutor)driver).executeScript("window.open('','_blank');");
            new WebDriverWait(driver, 10).until(ExpectedConditions.numberOfWindowsToBe(2));
            Set<String> allWindowHandles = driver.getWindowHandles();
            // Using iterator
            Iterator<String> itr = allWindowHandles.iterator();
            while(itr.hasNext()) {
                String nextWindow = itr.next();
                if(!firstWindowHandle.equalsIgnoreCase(nextWindow)) {
                    driver.switchTo().window(nextWindow);
                    System.out.println("New Tab Window Handle is: "+nextWindow);
                }
            }
        }
    }
    
  • Console Output:

    First Window Handle is: CDwindow-0D89767363ED691767000F01E6712D0B
    New Tab Window Handle is: CDwindow-7232D2058514ED22344F129D30A0CCE7
    
  • Browser Snapshot:

blank_tab


Usecase B: Opening an adjacent tab with an url and and iterating through an iterator

  • Code Block:

    import java.util.Iterator;
    import java.util.Set;
    
    import org.openqa.selenium.JavascriptExecutor;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.chrome.ChromeOptions;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    
    public class NewTab_url_forLoop {
    
        public static void main(String[] args) {
    
            System.setProperty("webdriver.chrome.driver","C:\\WebDrivers\\chromedriver.exe");
            ChromeOptions options = new ChromeOptions();
            options.addArguments("start-maximized");
            WebDriver driver =  new ChromeDriver(options); 
            String url1 = "https://mail.google.com/";
            String url2 = "https://www.facebook.com/";
            driver.get(url1);
            String firstWindowHandle = driver.getWindowHandle();
            System.out.println("First Window Handle is: "+firstWindowHandle);
            // Opening Facebook in the adjacent TAB
            ((JavascriptExecutor)driver).executeScript("window.open('" + url2 +"');");
            new WebDriverWait(driver, 10).until(ExpectedConditions.numberOfWindowsToBe(2));
            Set<String> allWindowHandles = driver.getWindowHandles();
            // Using iterator
            Iterator<String> itr = allWindowHandles.iterator();
            while(itr.hasNext()) {
                String nextWindow = itr.next();
                if(!firstWindowHandle.equalsIgnoreCase(nextWindow)) {
                    driver.switchTo().window(nextWindow);
                    System.out.println("New Tab Window Handle is: "+nextWindow);
                }
            }
        }
    }
    
  • Console Output:

    First Window Handle is: CDwindow-01F5622275A2EA2C1ABE2F0CDEB3D09B
    New Tab Window Handle is: CDwindow-9E3349B91FB2FA4D5B7D4A90D0E87BD3
    
  • Browser Snapshot:

url_tab


this below code works for me in Selenium 3 and chrome version 58.

    WebDriver driver = new ChromeDriver();
    driver.get("http://yahoo.com");  
    ((JavascriptExecutor)driver).executeScript("window.open()");
    ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
    driver.switchTo().window(tabs.get(1));
    driver.get("http://google.com");

I had used the below code to open a new tab in the browser using C# selenium..

IJavaScriptExecutor js = (IJavaScriptExecutor)driver;

js.ExecuteScript("window.open();");

Selenium 4 is already included this feature now, you can directly 
open new Tab or new Window with any URL. 

WebDriverManager.chromedriver().setup();

driver = new ChromeDriver(options);

driver.get("www.Url1.com");     
//  below code will open Tab for you as well as switch the control to new Tab
driver.switchTo().newWindow(WindowType.TAB);

// below code will navigate you to your desirable Url 
driver.get("www.Url2.com");

download Maven dependencies, this is what I downloaded - 

        <dependency>
            <groupId>io.github.bonigarcia</groupId>
            <artifactId>webdrivermanager</artifactId>
            <version>3.7.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency> 

    you can refer: https://codoid.com/selenium-4-0-command-to-open-new-window-tab/

    watch video : https://www.youtube.com/watch?v=7SpCMkUKq-Y&t=8s

google out for - WebDriverManager selenium 4

I have tried other techniques, but none of them worked, also no error produced, but when I have used the code below, it worked for me.

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

If you can get the link element you can use this. It will also take you to the tab that you have opened.

WebElement link= driver.findElement(By.tagname("a"));  
String keyString =   Keys.CONTROL+Keys.SHIFT.toString()+Keys.ENTER.toString());
link.sendKeys(keyString);

I am trying to do a robot to my little son and just play a Youtube video and than show a robot dancing.

For some reason, commands like CONTROL + T explained above was not working for me and maybe it is not the correct answer but I solved my problem using custom Javascript script like this:

using (var driver = new ChromeDriver())
            {
                var link1 = "https://www.youtube.com/watch?v=0GIgk4yuHOQ";
                //open a music
                driver.Navigate().GoToUrl(link1);
                var link2 = "https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/fbe53d6d-c13f-4eec-9bcf-62f19cfab15a/d4m0h4v-9442b1f2-6a49-4818-8f51-5ebe216f043c.gif?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ1cm46YXBwOjdlMGQxODg5ODIyNjQzNzNhNWYwZDQxNWVhMGQyNmUwIiwic3ViIjoidXJuOmFwcDo3ZTBkMTg4OTgyMjY0MzczYTVmMGQ0MTVlYTBkMjZlMCIsImF1ZCI6WyJ1cm46c2VydmljZTpmaWxlLmRvd25sb2FkIl0sIm9iaiI6W1t7InBhdGgiOiIvZi9mYmU1M2Q2ZC1jMTNmLTRlZWMtOWJjZi02MmYxOWNmYWIxNWEvZDRtMGg0di05NDQyYjFmMi02YTQ5LTQ4MTgtOGY1MS01ZWJlMjE2ZjA0M2MuZ2lmIn1dXX0.BTTlingNpBqH5O9dNVienFsArNqkfUc7KXnIgHumrBQ";
                //Dance robot, dance
                driver.ExecuteScript($"window.open('{link2}', '_blank');");
                Thread.Sleep(20000);
            }

First open empty new Tab by using the keys Ctrl + t and then use .get() to fetch the URL you want. Your code should look something like this -

String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,"t");
driver.findElement(By.tagName("body")).sendKeys(selectLinkOpeninNewTab);

driver.get("www.facebook.com");

If you want to open a link on the current view in a new tab then the code you've written above can be used. Instead of By.linkText() make sure you use the appropriate By selector class to select the web element.


The original poster is asking on how to open a link on a new tab. So this is how I have done it in C#.

        IWebDriver driver = new ChromeDriver();
        driver.Manage().Window.Maximize();
        driver.Navigate().GoToUrl("https://microsoft.com");
        IWebElement eventlink = driver.FindElement(By.Id("uhfLogo"));
        Actions action = new Actions(driver);
        action.KeyDown(Keys.Control).MoveToElement(eventlink).Click().Perform(); 

This actually performs a Control+Click on the selected element in order to open the link in a new tab.


You can open multiple browser or a window by using below code:

WebDriver driver = new ChromeDriver();
driver.get("http://yahoo.com");  

WebDriver driver1 = new ChromeDriver();
driver1.get("google.com");

WebDriver driver2 = new InternetExplorerDriver();
driver2.get("google.com/gmap");

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to google-chrome

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 SameSite warning Chrome 77 What's the net::ERR_HTTP2_PROTOCOL_ERROR about? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Jupyter Notebook not saving: '_xsrf' argument missing from post How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? 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 make audio autoplay on chrome How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

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 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?