Switch tabs using Selenium WebDriver with Java.

We can switch tabs using Selenium. First we have to open a link in a new tab. The Keys.chord method along with sendKeys is to be used. The Keys.chord method allows you to pass more than one key at once. The group of keys or strings are passed as arguments to the method.

We shall pass Keys.CONTROL and Keys.ENTER as arguments to the Keys.chord method. The whole string is then passed as an argument to the sendKeys method. Finally, the sendKeys method has to be applied on the link which is identified by driver.findElement method.


String clickl = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.xpath("//*[text()='Terms of Use']")). sendKeys(clickl);

Then hold all the opened window ids in an ArrayList and shift the driver focus to the new tab with the switchTo method. Then pass the window id of the new tab as an argument to that method.

Finally, after performing tasks on the new tab, we can shift back to the parent window with the switchTo method and pass window id of the parent window as an argument to that method.

Let us switch between the two tabs −


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 java.util.ArrayList;
public class SwitchTab{
   public static void main(String[] args) {
      WebDriver driver = new ChromeDriver();
      // wait of 5 seconds
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // Keys.Chord string
      String clickl = Keys.chord(Keys.CONTROL,Keys.ENTER);
      // open the link in new tab, Keys.Chord string passed to sendKeys
      By.xpath("//*[text()='Terms of Use']")).sendKeys(clickl);
      // hold all window handles in array list
      ArrayList<String> newTb = new ArrayList<String>(driver.getWindowHandles());
      //switch to new tab
      System.out.println("Page title of new tab: " + driver.getTitle());
      //switch to parent window
      System.out.println("Page title of parent window: " + driver.getTitle());


Updated on: 30-Nov-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started