How do I switch to the active tab in Selenium?

SeleniumAutomation TestingTesting Tools

We can switch to the active tab in Selenium. The methods Keys.chord and sendKeys are used to open a new tab. More than one key can be passed at once with the Keys.chord method.

The Keys.CONTROL and Keys.ENTER combined are passed as parameters to the Keys.chord method. This is stored as a string and again passed as a parameter to the sendKeys method.

Syntax

String tb = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.xpath("//*[text()='Company']")).sendKeys(tb);

All the window ids which are opened are stored in an array list. By default, the driver has the focus on the parent window. To switch the focus to the new tab, switchTo().window method is used.

The getWindowHandle method is used to hold the window id of the active tab and it is then passed as parameter to the switchTo().window method. The getWindowHandles method holds all the opened window ids.

Example

Code Implementation.

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 SwitchActiveTab{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      // wait of 5 seconds
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // Keys.Chord string
      String tb = Keys.chord(Keys.CONTROL,Keys.ENTER);
      driver.findElement(By.xpath("//*[text()='FAQ']")).sendKeys(tb);
      Thread.sleep(10000);
      // store window ids in array list
      ArrayList<String> wid = new ArrayList<String>(driver.getWindowHandles());
      //switch to active tab
      driver.switchTo().window(wid.get(1));
      System.out.println("Page title of active tab: " + driver.getTitle());
      //switch to parent
      driver.switchTo().window(newTb.get(0));
      System.out.println("Page title of parent window: " + driver.getTitle());
      driver.quit();
   }
}

Output

raja
Published on 28-Dec-2020 12:00:22
Advertisements