How to open a new tab using Selenium WebDriver?


We can open a new tab with Selenium. The Keys.chord and sendKeys methods are used for this. Multiple keys can be passed simultaneously with the Keys.chord method. A group of strings or keys can be passed as parameters to that method.

The Keys.CONTROL and Keys.ENTER are passed as parameters to the Keys.chord method here. This is stored as a string value and finally passed as a parameter to the sendKeys method.

Syntax

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

Example

Code Implementation.

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 OpnLinkNwTab{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      // wait of 4 seconds
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // Keys.Chord string
      String nwtb = Keys.chord(Keys.CONTROL,Keys.ENTER);
      // open the link in new tab, Keys.Chord string passed to sendKeys
      driver.findElement(
      By.xpath("//*[text()='Company']")).sendKeys(nwtb);
   }
}

Output

Updated on: 28-Dec-2020

986 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements