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.


Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
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("", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // window handles
      Set wnd = driver.getWindowHandles();
      // window handles iterate
      Iterator i = wnd.iterator();
      String popwnd =;
      String prntw =;
      // switching pop up tab
      System.out.println("Page title of popup: "+ driver.getTitle());
      // closes all windows


Updated on: 26-Oct-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started