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.

Similar Posts from the author:

24 thoughts to “How to open a link in a new tab or window and switch to it with Selenium WebDriver

  • Roselin

    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.

    • Tihomir Turzai

      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/

  • Rose

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

    • Szabolcs Berkó

      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! 🙂

      • Anonymous

        Save my day! Thanks

      • Pankaj

        Awesome. Thankyou much

      • shyamala

        hi this shyamala i want code in open new window not new tab pls tell me code

  • Saravanakumar

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

    • Szabolcs Berkó

      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! 🙂

  • Srinivasan

    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

      I Can’t able to switch to new window

      • Árpád Farkas

        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.

  • Mandeep

    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

      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…….

  • nageswarao

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

  • Ajay

    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

    • Ivan Konjević

      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);
      
  • Amitesh Srivastava

    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 🙂

  • Ajay

    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

    • Dane Dukić

      Hi Ajay,
       
      You can do this in many ways, easiest is:

      driver.get("https://www.wedoqa.com");
      
      driver.navigate().refresh();

      or you can send “F5” key to one of the elements on the page

      driver.get("https://www.wedoqa.com");
      
      // Element "s" is a Seach Text box on my website
      
      driver.findElement(By.name("s")).sendKeys(Keys.F5);

       
      Regards

  • Rohit

    Hi , thank you for the code .
    I need help regarding the same issue . I have a table of javascript links . When i click on first link through code , it loads the new page and clicks on a specific link on the loaded page(‘which is good) but i am not able to get back to initial result page and perform the same task for next 100 or more links automatically through code .

    Please Help !!!!

    • Dane Dukić

      Hi Rohit,
      Can you please provide sample with same behavior? (some URL of it would be great) It is hard to manipulate with javascript links, but usually there is alternative way to do this.
      Regards

  • vishal

    can any one help with the java code for the scenario clicking each get result of google search , clicking each link in the new tab and close each tab and verify title of each page.

    appreciate any help

    • Tamás Kovacsics

      Hi vishal

      Here is an example for google search, it will open every usual result (ignoring suggestion to search for images) in new tab, the same window as the search.

      To open the results in a new window instead of tab replace CONTROL key with SHIFT

      I hope it helps

          @Test
          public void openGoogleSearchInNewTabInChrome(){
              WebDriver driver = new ChromeDriver();
              driver.get("http://www.google.com");
      
              driver.findElement(By.cssSelector("input[title]")).sendKeys("wedoqan");
              List results = driver.findElements(By.cssSelector(".rc h3 a"));
              for (WebElement link: results) {
                  Actions actionOpenLinkInNewTab = new Actions(driver);
                  actionOpenLinkInNewTab.moveToElement(link)
                  .keyDown(Keys.CONTROL)
                  .click(link)
                  .keyUp(Keys.CONTROL)
                  .perform();
      
                  ArrayList tabs = new ArrayList(driver.getWindowHandles());
                  driver.switchTo().window(tabs.get(1));
      
                  //verify title
                  System.out.println(driver.getTitle());
      
                  driver.close();
      
                  driver.switchTo().window(tabs.get(0));
              }
      
              driver.quit();
          }
      

Comments are closed.