Using window handles to switch to another tab (window) with Selenium WebDriver (Java)

with No Comments

Some apps have different integrations with other apps. When we have connection with other apps we pass authorisation form or something like this. 

For instance, for using Selenium WebDriver you click on button which openeds new window ( or tab). To continue your steps in a test case you should click on a button which is located in another tab. So if you use this code, it doesn’t work for you.    

 

@Test // Marking this method as part of the test

public void gotoTestURL() {

  // Go to the Test page

  driver.get(“https://test.io/become-a-tester/”);

  // Find an element and click on it to open an url in a new tab

  WebElement Example  = driver.findElement(By.xpath(“//*[@id=\”masthead\”]/div/div/div[1]/div[3]/div/a[1]”));

  Example.click();

  // Wait for loading the page in a new tab

  try {

      Thread.sleep(TestConstants.DEFAULT_WAIT_TIME);

  } catch (InterruptedException e) {

      e.printStackTrace();

  }

// Click on ” Login” field and set credentials in this field which is located on the other tab

  }

      driver.findElement(By.id(“session_email”)).sendKeys(“test@test.com”);

 

After running the test you can see “Unable to locate element: #session_email” error which is appeared in your environment. And it is happened because your driver findound an element on the same page. So, you should use different variants of handling window to move to another tab ( or window) and continue you test case.

There are a lot of different simple possible variants to switch to another window. One of them you can see below:

 

driver.switchTo().window(“windowName”);

 

Of course, it can not work because of different reasons..So, you can use this part of code

 

for (String window2 : driver.getWindowHandles()) {

      driver.switchTo().window(window2);

 

before finding an element in an opened tab or window . See my sample below:

 

@Test // Marking this method as part of the test

public void gotoTestURL() {

  // Go to the Test page

  driver.get(“https://test.io/become-a-tester/”);

  // Find an element and click on it to open an url in a new tab

  WebElement Example  = driver.findElement(By.xpath(“//*[@id=\”masthead\”]/div/div/div[1]/div[3]/div/a[1]”));

  Example.click();

  // Wait for loading the page in a new tab

  try {

      Thread.sleep(TestConstants.DEFAULT_WAIT_TIME);

  } catch (InterruptedException e) {

      e.printStackTrace();

  }

 

  // Switch to new tab (window) which is opened

 

  for (String window2 : driver.getWindowHandles()) {

      driver.switchTo().window(window2);

}

      // Click on ” Login” field and set credentials in this field

  

      driver.findElement(By.id(“session_email”)).sendKeys(“test@test.com”);

  }

 

Leave a Reply