14

How to open a new tab using Selenium WebDriver?

I want to open multiple links in new tabs. This is to achieve to finish off the build validation tasks as soon as possible. So, that in every new tab all smoke test related links could be opened and then within each tab which corresponds to a smoke test requirement, we can carry out the sanity test.

Harsh Nigam
  • 465
  • 2
  • 6
  • 22
  • 1
    possible duplicate of [How to open a new tab using Selenium WebDriver?](http://stackoverflow.com/questions/17547473/how-to-open-a-new-tab-using-selenium-webdriver) – Ajinkya Apr 11 '14 at 12:21
  • 1
    Not a duplicate ... this is about opening a LINK in a new tab - that other one is about opening a completely new tab. – Brondahl Oct 01 '14 at 17:38
  • Possible duplicate of [Open a new tab in an existing browser session using Selenium](https://stackoverflow.com/questions/41587533/open-a-new-tab-in-an-existing-browser-session-using-selenium) – Gokul Aug 11 '17 at 14:04

8 Answers8

8

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");
Alex Mathew
  • 340
  • 1
  • 3
  • 12
  • The above Robot code is worked for me to open a new tab only. But 2nd URL (http://facebook.com) is not opened in 2nd tab as it is not switched to 2nd tab. It needs to switch to 2nd tab – Ripon Al Wasim Jul 19 '17 at 09:08
  • Typing error in code. Replace `driver.` with `wd.`. For some reason edit is rejected. – Luke Jan 19 '18 at 11:25
5

The only way to open links in new tabs is by simulating key-board shortcuts. The following hold true in FFX, Chrome & IE

  1. Ctrl+t will open a blank new tab, and switch focus to it.
  2. Holding Ctrl, then clicking the link will open the link in a new tab but leave focus on the existing tab.
  3. Holding Ctrl AND Shift, then clicking will open the link in a new tab AND move focus onto the new tab.
  4. 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.

Brondahl
  • 7,402
  • 5
  • 45
  • 74
2

/* 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));

}
Prasanth RJ
  • 137
  • 1
  • 8
1

We can use the Actions class of WebDriver. See following code:

WebDriver driver = new FirefoxDriver();
driver.get("<provide URL>");
WebElement link = driver.findElement(locator);
Actions builder = new Actions(driver);
Action openLinkInNewTab = builder
         .moveToElement(link)
         .sendKeys(link, Keys.CONTROL)
         .click(link)
         .keyUp(Keys.CONTROL)
         .build();

openLinkInNewTab.perform();

This can be looped for multiple links.

Sitam Jana
  • 3,123
  • 2
  • 21
  • 40
  • If you've moved the mouse to the element, then you don't need to provide the element when you `click()` it. using `sendKeys()` doesn't do anything because by the time you run `click()` the control key has stopped being pressed. And then when you call `keyUp()` it crashes because the Control key is ALREADY up. – Brondahl Sep 29 '14 at 18:31
1
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test; 

import java.awt.Robot;
import java.awt.event.KeyEvent;

import java.awt.AWTException; 



public class Tabs {

 WebDriver driver; 

 Robot rb;



 @BeforeTest
 public void setup() throws Exception {
  System.setProperty("webdriver.chrome.driver", "C:\\Users\\Anuja.AnujaPC\\Downloads\\chromedriver_win32\\chromedriver.exe");
  WebDriver driver=new ChromeDriver();
  driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
  driver.get("http://qaautomated.com");
 }

 @Test
 public void openTab() {
  //Open tab 2 using CTRL + t keys.
  driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");


 //Open URL In 2nd tab.
  driver.get("http://www.qaautomated.com/p/contact.html");

  //Call switchToTab() method to switch to 1st tab
  switchToTab(); 



  //perform required actions on tab 1.
  driver.findElement(By.xpath("//input[@id='6']")).click();
  driver.findElement(By.xpath("//input[@id='plus']"));
  driver.findElement(By.xpath("//input[@id='3']"));
  driver.findElement(By.xpath("//input[@id='equals']"));

  //Call switchToTab() method to switch to 2nd tab.
  switchToTab();

  //Call switchToTab() method to switch to 1st tab
  switchToTab();


 } 

 public void switchToTab() {
  //Switching between tabs using CTRL + tab keys.
  driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");
  //Switch to current selected tab's content.
  driver.switchTo().defaultContent();  
 } 



@AfterTest
 public void closeTabs() throws AWTException {
  //Used Robot class to perform ALT + SPACE + 'c' keypress event.
  rb =new Robot();
  rb.keyPress(KeyEvent.VK_ALT);
  rb.keyPress(KeyEvent.VK_SPACE);
  rb.keyPress(KeyEvent.VK_C);
 } }

This example is taken from THIS BLOG POST

anuja jain
  • 1,367
  • 13
  • 19
0
// To open a new tab to establish second player connection
        ((JavascriptExecutor)driver).executeScript("window.open('about:blank', '-blank')");
        // To switch to the new tab
        ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
        driver.switchTo().window(tabs.get(1));
        // To navigate to new link/URL in 2nd new tab
        driver.get("http://localhost:8080");

I did this and it worked perfect!

Cowarrior
  • 15
  • 1
  • 5
0

In the first solution, add a Thread.sleep(5000) statement. I had error Index out of bounds multiple times, until i added the sleep statement.

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);    

try {Thread.sleep(5000);} catch (InterruptedException e) {}

//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");
-1

The above solutions did not work for me. Not sure why, but the driver would navigate to the new url, but a new tab just won't open.

I finally managed to open new tab using this code:

IWebDriver driver = new ChromeDriver("path for chromedriver.exe");
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
driver.Navigate().GoToUrl("url1");
js.ExecuteScript("window.open()");
driver.SwitchTo().Window(driver.WindowHandles[driver.WindowHandles.Count - 1]);
driver.Navigate().GoToUrl("url2");

driver.WindowHandles.Count - 1 will get you the last opened tab i.e. the new tab in this scenario. Hope this helps someone out.

Prashant Tiwari
  • 346
  • 1
  • 3
  • 17