0

I am trying to open new tab in selenium using below line of code

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

But tabs is not opening up. Can anyone tell whats wrong in this command? Also can any one explain "driver.findElement(By.cssSelector("body"))" used in this command for ? I tried searching but not proper answers

Below complete is not working. It is opening up both gmail and stack overflow in same tab in chrome not opening up new tab

package TestCode;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Chrome {

    public static void main(String[] args) throws InterruptedException {
        // TODO Auto-generated method stub

        System.setProperty("webdriver.chrome.driver","C:\\Akash\\Drivers\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.gmail.com");
        String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL+"t"); 
        driver.findElement(By.tagName("body")).sendKeys(selectLinkOpeninNewTab);
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://stackoverflow.com/");
        System.out.println("Site open");
    }

}
Akash Chavan
  • 325
  • 2
  • 7
  • 22

2 Answers2

3

You can use javaScripts to open new tab in chrome.

try below line of code

  JavascriptExecutor js = (JavascriptExecutor) driver; 
 js.executeScript("window.open('https://www.google.com','_blank');");

Refer this link :- link

Ankur Singh
  • 1,239
  • 1
  • 8
  • 18
  • windows.open() is implemented differently for different browser for chrome it is working fine, for chrome it is opening new tab but for firefox it is opening new browser :( – Akash Chavan Aug 24 '17 at 06:56
  • No it will be same for firefox also i have tried and it's working fine for pe..type this in firefox console window.open("https://www.google.com","_blank"); – Ankur Singh Aug 24 '17 at 06:59
  • In console it opens new tab for firefox but in test script it is opening new window – Akash Chavan Aug 24 '17 at 07:40
  • String currentUrl = getCurrentUrl();JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript("window.open('"+currentUrl+"','_blank');"); – Akash Chavan Aug 25 '17 at 10:25
0

Instead of chord use control

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

For chrome use this

first opened the tab and then hit the URL

String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL+"t"); 
driver.findElement(By.tagName("body")).sendKeys(selectLinkOpeninNewTab);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://stackoverflow.com/");
System.out.println("Site open");
iamsankalp89
  • 4,607
  • 2
  • 15
  • 36