How to open a link in new tab using Selenium WebDriver?


We can open a link in the new tab with Selenium. . The methods Keys.chord and sendKeys can be used for this. The Keys.chord method allows you to pass multiple keys simultaneously.

We shall send Keys.CONTROL and Keys.ENTER as arguments to the Keys.chord method. Then the complete string is then passed as an argument to the sendKeys method. Finally, the sendKeys method has to be applied on the link which is identified by driver.findElement method.

Syntax

String clicklnk = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.xpath("//*[text()='Privacy Policy']")). sendKeys(clicklnk);

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class OpenInNwTab{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // wait of 4 seconds
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      // Keys.Chord string
      String clicklnk = Keys.chord(Keys.CONTROL,Keys.ENTER);
      // open the link in new tab, Keys.Chord string passed to sendKeys
      driver.findElement(
      By.xpath("//*[text()='Privacy Policy']")).sendKeys(clicklnk);
   }
}

Output

Updated on: 30-Nov-2020

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements