The following codes are works both in Firefox and Chrome browsers.

Open a link in a new window and switch to it:


WebElement link = getMyDriver().findElement(By.xpath("//*[@id='link']"));
Actions newTab = new Actions(getMyDriver());
newTab.keyDown(Keys.SHIFT).click(link).keyUp(Keys.SHIFT).build().perform();
Thread.sleep(5000);

//handle windows change
String base = getMyDriver().getWindowHandle();
Set<String> set = getMyDriver().getWindowHandles();

set.remove(base);
assert set.size() == 1;
getMyDriver().switchTo().window((String) set.toArray()[0]);

//close the window
getMyDriver().close();
getMyDriver().switchTo().window(base);

// handle windows change and switch back to the main window
Thread.sleep(2500);
for (String winHandle : getMyDriver().getWindowHandles()) {
getMyDriver().switchTo().window(winHandle);
}

First create a WebElement to the link. Now we need an Action chain to press Shift key and then click to the link.
It will open the link in a new window.

Now we need to handle the window change.
First we set the main window to a String with getWindowHandle().
The second step is to get all the windows to a list with getWindowsHandles();
Now we remove the base window from the list and assert that the list size is 1.
After this we need to switch to the new window with the WebDriver:
getMyDriver().switchTo().window((String) set.toArray()[0]);

To close the window and switch back to the main window, use the following steps:
getMyDriver().close();
getMyDriver().switchTo().window(base);

Just for sure it was switched to the main window use the following window handles:
for (String winHandle : getMyDriver().getWindowHandles()) {
getMyDriver().switchTo().window(winHandle);
}

Open a link in a new tab and switch to it:


WebElement link = getMyDriver().findElement(By.xpath("//*[@id='link']"));
Actions newTab = new Actions(getMyDriver());
newTab.keyDown(Keys.CONTROL).keyDown(Keys.SHIFT).click(link).keyUp(Keys.CONTROL).keyUp(Keys.SHIFT).build().perform();
Thread.sleep(5000);

//handle windows change
String base = getMyDriver().getWindowHandle();
Set<String> set = getMyDriver().getWindowHandles();

set.remove(base);
assert set.size() == 1;
getMyDriver().switchTo().window((String) set.toArray()[0]);

//close the window and sitch back to the base tab
getMyDriver().close();
getMyDriver().switchTo().window(base);

If we want to open the link in a new tab than we need to use the following action chain:
newTab.keyDown(Keys.CONTROL).keyDown(Keys.SHIFT) .click(link).keyUp(Keys.CONTROL).keyUp(Keys.SHIFT).build().perform();

It press CTRL+SHIFT keys then click to the link.

The other steps are similar with the steps we used in “switch-to-new-window” code above.

Posted By István Lackó

    19 Responses to “How to open a link in a new tab or window and switch to it with Selenium WebDriver”

  1. Roselin says:

    Please provide me a complete program; How to open a new tab and has to work with it and after that we have to come back to previous tab. Plz tell me what package i have to install; I struced over their in my project from past 2 days. Plz provide me a solution.

    • Hi Roselin,

      The example code in the post explains you how to open a new tab and how to work with it,if you have any specific problems with the code or something then please provide us some details of the error. As for the imports we only used the standard selenium packages which can be downloaded from their official site. http://www.seleniumhq.org/download/

  2. Rose says:

    Please provide me a complete program; that may helps to learn, that how to open a link in new tab and switch to it.

    • Hi Rose!
      Thank you for your comment. The article was posted a long time ago, so I will introduce to you two ways with todays version of Selenium. I will introduce it with a little test case:
      1. Open http://www.google.com
      2. Open a new tab and switch to it
      3. Open http://www.yahoo.com in the new tab
      Unfortunately there is no cross browser solution for manipulating with tabs, so I will show to you separate solutions for Chrome and Firefox also.
      Here is the solution for Chrome:

      @Test
      	public void openNewTabInChrome(){
      		WebDriver driver = new ChromeDriver();
      		driver.get(&quot;http://www.google.com&quot;);
      		
      		WebElement element = driver.findElement(By.linkText(&quot;Gmail&quot;));
      		Actions actionOpenLinkInNewTab = new Actions(driver);
      		actionOpenLinkInNewTab.moveToElement(element)
      								.keyDown(Keys.COMMAND)
      								.keyDown(Keys.SHIFT)
      								.click(element)
      								.keyUp(Keys.COMMAND)
      								.keyUp(Keys.SHIFT)
      								.perform();
      		
      		ArrayList tabs = new ArrayList (driver.getWindowHandles());
      		driver.switchTo().window(tabs.get(1));
      		driver.get(&quot;http://www.yahoo.com&quot;);
      		driver.close();
      		
      		driver.switchTo().window(tabs.get(0));
      		driver.get(&quot;http://www.yahoo.com&quot;);
      		
      		driver.close();
      	}
      

      Here is the solution for Firefox:

      @Test
      	public void openNewTabInFirefox(){
      		WebDriver driver = new FirefoxDriver();
      		driver.get(&quot;http://www.google.com&quot;);
      		
      		WebElement body = driver.findElement(By.cssSelector(&quot;body&quot;));
      		String newTabAction = Keys.chord(Keys.COMMAND, &quot;t&quot;);
      		body.sendKeys(newTabAction);
      		
      		String chooseTab = Keys.chord(Keys.COMMAND, &quot;2&quot;);
      		body.sendKeys(chooseTab);
      		
      		driver.get(&quot;http://www.yahoo.com&quot;);
      		
      		driver.close();
      	}
      

      Feel free to ask any question!
      Have a good day! 🙂

  3. Saravanakumar says:

    Your code snippet does not open new window in Chrome!. Rather it clicks the link in the same window only

    • Hi Saravanakumar!

      Thank you for your comment. I tried out the first code snippet (“Open a link in a new window and switch to it”) and for me it’s working ok. Please provide to us detailed information about your setup.

      However here is a simpler solution. It will maybe help you:

      @Test
      	public void openNewWindowInChrome(){
      		WebDriver driver = new ChromeDriver();
      		driver.get(&quot;http://www.google.com&quot;);
      		
      		WebElement element = driver.findElement(By.linkText(&quot;Gmail&quot;));
      		Actions actionOpenLinkInNewTab = new Actions(driver);
      		actionOpenLinkInNewTab.moveToElement(element)
      								.keyDown(Keys.SHIFT)
      								.click(element)
      								.keyUp(Keys.SHIFT)
      								.perform();
      		
      		ArrayList tabs = new ArrayList (driver.getWindowHandles());
      		driver.switchTo().window(tabs.get(1));
      		driver.get(&quot;http://www.yahoo.com&quot;);
      		driver.close();
      		
      		driver.switchTo().window(tabs.get(0));
      		driver.get(&quot;http://www.yahoo.com&quot;);
      		
      		driver.close();
      	}
      

      Feel free to ask any question!
      Have a good day! 🙂

  4. Srinivasan says:

    How to switch focus to new window using javascriptexecutor.

    below code:
    Actions action = new Actions(driver);
    WebElement maninmenu = driver.findElement(By.id(“menu2”))action.moveToElement(maninmenu);
    action.clickAndHold(maninmenu).build().perform();
    Thread.sleep(5000);
    String originalHandle = driver.getWindowHandle();
    WebElement tmpElement= driver.findElement(By.xpath(“//*[@id=’smenu2′]/input[8]”));
    JavascriptExecutor executor = (JavascriptExecutor)driver;
    executor.executeScript(“arguments[0].click();”, tmpElement);

    Actions action = new Actions(driver);
    WebElement maninmenu = driver.findElement(By.id(“menu2”));
    action.moveToElement(maninmenu);
    action.clickAndHold(maninmenu).build().perform();
    Thread.sleep(5000);

    • Srinivasan says:

      I Can’t able to switch to new window

      • Hello Srinivasan!
        It is not possible to say what could be the problem with the code from that snippet, but there is a solution which could work and you do not even need to use JavaScript. The WebDriver’s window handlers can solve you problem. Just like:

        for(String winHandle : driver.getWindowHandles()){
            driver.switchTo().window(winHandle);
        }

        This is the official documentation of window handlers:
        Selenium Google Code – Window handler
        Feel free to contact us with any further questions.

  5. Mandeep says:

    i need to open new tab in same browser and perform actions in IE i able to do same in chrome and firefox using protractor.Can anybody help me plz??

    • Anupama says:

      See if /uncheck enable protected mode in security settings of IE browser because that gave me a lot of issues in IE.Comparatively new with Selelnium.Just letting you know what worked for me…….

  6. nageswarao says:

    test secanario: in google we search something.page display more number of links.if select any link to new window how to automate….

  7. Ajay says:

    Hi All,

    Is there a way to take screenshot of the window after switching it.
    I tied with driver but it still takes pics of parent window.

    Thanks,
    Ajay

    • Hello Ajay!
      The driver will take the screenshot of the current window, so once you switch to the desired window you should be fine.
      Here are few lines that might help you out:

       List&lt;String&gt; windows = new ArrayList&lt;String&gt; (driver.getWindowHandles());
              driver.switchTo().window(windows.get(1));
              File screenshot =  ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
      
  8. Amitesh Srivastava says:

    Thanks a lot for the code.
    “newTab.keyDown(Keys.SHIFT).click(link).keyUp(Keys.SHIFT).build().perform();”
    This single line has solved my long term question of handling new tabs 🙂

  9. Ajay says:

    I want to refresh browser page already open in browser tab.
    Is it possible using selenium.
    Is it possible if browser is already open, we open url in same browser new tab instead of every time start new browser using selenium.

    Please help me, Its Urgent.

    Regards
    Ajay

Leave a Reply




XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>