How to open a new tab in the existing Firefox browser using Selenium WebDriver (a.k.a. Selenium 2)?
*JAVA
I recommend to using JavascriptExecutor
:
((JavascriptExecutor) driver).executeScript("window.open()");
((JavascriptExecutor) driver).executeScript("window.open('https://google.com')");
Following import:
import org.openqa.selenium.JavascriptExecutor;
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(0));
Just for anyone else who's looking for an answer in Ruby/Python/C# bindings (Selenium 2.33.0).
Note that the actual keys to send depend on your OS, for example, Mac uses COMMAND + t
, instead of CONTROL + t
.
Ruby
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
driver.get('http://stackoverflow.com/')
body = driver.find_element(:tag_name => 'body')
body.send_keys(:control, 't')
driver.quit
Python
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/")
body = driver.find_element_by_tag_name("body")
body.send_keys(Keys.CONTROL + 't')
driver.close()
C#
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace StackOverflowTests {
class OpenNewTab {
static void Main(string[] args) {
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://stackoverflow.com/");
IWebElement body = driver.FindElement(By.TagName("body"));
body.SendKeys(Keys.Control + 't');
driver.Quit();
}
}
}
To open a new tab in the existing Chrome browser using Selenium WebDriver you can use this code:
driver.FindElement(By.CssSelector("body")).SendKeys(Keys.Control + "t");
string newTabInstance = driver.WindowHandles[driver.WindowHandles.Count-1].ToString();
driver.SwitchTo().Window(newTabInstance);
driver.Navigate().GoToUrl(url);
This line of code will open a new browser tab using selenium webdriver
((JavascriptExecutor)getDriver()).executeScript("window.open()");