How to open a new tab in the existing Firefox browser using Selenium WebDriver (a.k.a. Selenium 2)?
You can use the following code using Java with Selenium WebDriver:
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL + "t");
By using JavaScript:
WebDriver driver = new FirefoxDriver();//FF or any other Driver
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.open()");
After opening new tab it needs to switch to that tab:
ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
Same example for nodejs:
var webdriver = require('selenium-webdriver');
...
driver = new webdriver.Builder().
withCapabilities(capabilities).
build();
...
driver.findElement(webdriver.By.tagName("body")).sendKeys(webdriver.Key.COMMAND + "t");
If you want to open the new tab you can use this
((JavascriptExecutor) getDriver()).executeScript("window.open()");
If you want to open the link from the new tab you can use this
with JavascriptExecutor:
public void openFromNewTab(WebElement element){
((JavascriptExecutor)getDriver()).executeScript("window.open('"+element.getAttribute("href")+"','_blank');");
}
with Actions:
WebElement element = driver.findElement(By.xpath("your_xpath"));
Actions actions = new Actions(driver);
actions.keyDown(Keys.LEFT_CONTROL)
.click(element)
.keyUp(Keys.LEFT_CONTROL)
.build()
.perform();
//to open new tab in existing window
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
This code working for me (selenium 3.8.1, chromedriver=2.34.522940, chrome=63.0):
public void openNewTabInChrome() {
driver.get("http://www.google.com");
WebElement element = driver.findElement(By.linkText("Gmail"));
Actions actionOpenLinkInNewTab = new Actions(driver);
actionOpenLinkInNewTab.moveToElement(element)
.keyDown(Keys.CONTROL) // MacOS: Keys.COMMAND
.keyDown(Keys.SHIFT).click(element)
.keyUp(Keys.CONTROL).keyUp(Keys.SHIFT).perform();
ArrayList<String> tabs = new ArrayList(driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
driver.get("http://www.yahoo.com");
//driver.close();
}
Try this for the FireFox browser.
/* Open new tab in browser */
public void openNewTab()
{
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(0));
}