How to open a new tab using Selenium WebDriver and start the link?
Code:
WebDriver wd = new FirefoxDriver();
wd.get("http://www.gmail.com");
wd.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
wd.manage().window().maximize();
//To open a new tab
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_T);
r.keyRelease(KeyEvent.VK_CONTROL);
r.keyRelease(KeyEvent.VK_T);
//To switch to the new tab
ArrayList<String> tabs = new ArrayList<String>(wd.getWindowHandles());
wd.switchTo().window(tabs.get(1));
//To navigate to new link/URL in 2nd new tab
wd.get("http://facebook.com");
The only way to open links in new tabs is by simulating key-board shortcuts. The following hold true in FFX, Chrome & IE
- Ctrl+t will open a blank new tab, and switch focus to it.
- Holding Ctrl, then clicking the link will open the link in a new tab but leave focus on the existing tab.
- Holding Ctrl AND Shift, then clicking will open the link in a new tab AND move focus onto the new tab.
- Ctrl+w will close the current tab and switch focus to the last open tab (although note that Ctrl+W i.e. Ctrl+Shift+w will close ALL tabs!)
Selenium doesn't (currently) have any concept of tabs within a browser window, so in order to open the tab and then test it you HAVE to use option 3.
The following code will execute option 3. and then immediately close that new tab. (In C#)
new Actions(WebDriver)
.KeyDown(Keys.Control)
.KeyDown(Keys.Shift)
.Click(tab)
.KeyUp(Keys.Shift)
.KeyUp(Keys.Control)
.Perform();
new Actions(WebDriver)
.SendKeys(Keys.Control + "w")
.Perform();
You could also use:
.MoveToElement(tab)
.Click()
in the middle of the first option, and
.KeyDown(Keys.Control)
.KeyDown("w")
.KeyUp("w")
.KeyUp(Keys.Control)
in the second one.