2

this is my line to open the new tab

 driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
aviau
  • 127
  • 1
  • 1
  • 7
user3080885
  • 63
  • 1
  • 1
  • 6
  • 3
    I would *not* recommend using tabs. They aren't supported in selenium. It will work, but trying to run commands on different tabs isn't a good way to have multiple processes. – Nathan Merrill Apr 19 '14 at 23:17
  • The above code works only in FF not in Chrome. For Chrome you can use JS – Ripon Al Wasim Jul 19 '17 at 07:04

5 Answers5

5
((JavascriptExecutor)driver).executeScript("window.open();");

This JavaScript code opens a new tab for the Chrome browser.

Pang
  • 9,564
  • 146
  • 81
  • 122
user7181273
  • 51
  • 1
  • 1
4

Use Actions class in WebDriver to do this. Below is a sample code:

WebDriver driver = new ChromeDriver();
driver.navigate().to("<URL>");
WebElement element = driver.findElement(By.cssSelector("body"));
Actions actionOpenLinkInNewTab = new Actions(driver);
actionOpenLinkInNewTab.moveToElement(element).keyDown(Keys.CONTROL).click(element).keyUp(Keys.CONTROL).perform();
Sitam Jana
  • 3,123
  • 2
  • 21
  • 40
1

this following code works for me in selenium 3 and chrome 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");
nur
  • 517
  • 4
  • 5
0

Try this code:

    Actions newTab = new Actions(webDriver);
    newTab.sendKeys(Keys.CONTROL + "t").perform();

Hope it will help.

Andrii
  • 357
  • 2
  • 9
0

Your code works in Firefoxdriver but not in Chromedriver. One solution is that you can open any link on current page into new tab. Following is the Python code for it.

actions = ActionChains(driver)
home_link = driver.find_element_by_class_name("logo")
actions.move_to_element(home_link)
actions.send_keys(Keys.CONTROL+ Keys.SHIFT)
actions.click(home_link)
actions.perform()
Dhiraj
  • 481
  • 6
  • 13