How to open new tab in same browser and switch between them using Selenium?


We can open new tabs in the same browser and switch between them using Selenium webdriver. Firstly, to open a new tab in the same browser we have to take the help of the methods – Keys.chord and sendKeys.

The parameters Keys.CONTROL and Keys.ENTER are passed to the Keys.chord method. This method yields a string value and in turn passed as a parameter to the sendKeys method.

Syntax

String n = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.id("open-tab")).sendKeys(n);

Once the second tab is opened, the getWindowHandles method is used to hold all the window handle ids in a Set. To shift the focus of the webdriver object to the new tab, the method switchTo().window is used.

The window handle id of the new tab should be passed as a parameter to the switchTo().window to shift the driver focus to the new tab. The method getWindowHandle is used to obtain the window handle id of the browser window in focus.

Let us open the link Team in a new tab in the same browser −

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
import org.openqa.selenium.Keys;
import java.util.ArrayList;
public class SwitchNewTab{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // method Keys.chord
      String n = Keys.chord(Keys.CONTROL, Keys.ENTER);
      //open link in new tab
      driver.findElement(By.linkText("Team")).sendKeys(n);
      Thread.sleep(8000);
      // store window handle ids
      ArrayList<String> w = new ArrayList<String>(driver.getWindowHandles());
      //switch to open tab
      driver.switchTo().window(w.get(1));
      System.out.println("New tab title: " + driver.getTitle());
      //switch to first tab
      driver.switchTo().window(w.get(0));
      System.out.println("First tab title: " + driver.getTitle());
      driver.quit();
   }
}

Output

Updated on: 07-Apr-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements