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.

Syntax

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 −

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 java.util.ArrayList;
public class SwitchTab{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
      "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // 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
      driver.findElement(
      By.xpath("//*[text()='Terms of Use']")).sendKeys(clickl);
      Thread.sleep(1000);
      // hold all window handles in array list
      ArrayList<String> newTb = new ArrayList<String>(driver.getWindowHandles());
      //switch to new tab
      driver.switchTo().window(newTb.get(1));
      System.out.println("Page title of new tab: " + driver.getTitle());
      //switch to parent window
      driver.switchTo().window(newTb.get(0));
      System.out.println("Page title of parent window: " + driver.getTitle());
      driver.quit();
   }
}

Output

Updated on: 30-Nov-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements