How do I change focus to a new popup tab in Selenium?


We can change focus to a new popup tab with Selenium webdriver. The getWindowHandles and getWindowHandle methods are available to handle new popup tabs. The getWindowHandles method stores all the currently opened window handles in Set data structure.

The getWindowHandle method stores the window handle of the opened browser in focus. The iterator method is used to iterate over all the window handle ids. We have to add import java.util.Set to accommodate Set and import java.util.List and import java.util.Iterator statements to accommodate the iterator in our code.

Selenium driver object can access the elements of the parent window. In order to switch its focus from the parent to the new popup tab, we shall take the help of the switchTo().window method and pass the window handle id of the popup as an argument to the method.

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.Set;
import java.util.Iterator;
public class SwitchToPopup {
   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://secure.indeed.com/account/login");
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.findElement(By.id("login-google-button")).click();
      // window handles
      Set wnd = driver.getWindowHandles();
      // window handles iterate
      Iterator i = wnd.iterator();
      String popwnd = i.next();
      String prntw = i.next();
      // switching pop up tab
      driver.switchTo().window(popwnd);
      System.out.println("Page title of popup: "+ driver.getTitle());
      // closes all windows
      driver.quit();
   }
}

Output

Updated on: 26-Oct-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements