Handle Popup in Selenium

Profile picture for user arilio666

The switchto() method can easily handle popups or new windows in Selenium.

In Selenium, you can use the switchTo() method to switch between different windows or tabs. You can use the switchTo() to switch to a specific  window.window() method and pass the name or handle of the window as an argument.

Here's an example of how you can switch to a new window in Selenium using Java:

// Get the current window handle
String currentWindow = driver.getWindowHandle();
// Click on a link that opens a new window
driver.findElement(By.linkText("Open new window")).click();
// Get the handles of all open windows
Set<String> windowHandles = driver.getWindowHandles();
// Iterate through the handles and switch to the new window
for (String handle : windowHandles) {
   if (!handle.equals(currentWindow)) {
       driver.switchTo().window(handle);
   }
}
// Perform actions on the new window
driver.findElement(By.id("search-box")).sendKeys("Selenium");
driver.findElement(By.id("search-button")).click();
  • You can also use the switchTo().defaultContent() method to switch back to the main window or use the currentwindow handle to switch back.
  • And when you are done with the new window, you can also close it with driver.close() method.

And finally, switch back to your main window using the current handle.

driver.switchTo().window(currentWindow);

Example:

  • We will be using the programsbuzz site as a real-time example.
  • Clicking the Facebook icon on the homepage will open a popup window that needs to be handled.

import org.openqa. Selenium.By;
import org.openqa. Selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class PopUp {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        WebDriverManager.chromedriver().setup();
        ChromeDriver driver = new ChromeDriver();
        driver.get("https://www.programsbuzz.com/");
        driver.manage().window().maximize();
        String currentWindow = driver.getWindowHandle();
        driver.findElement(By.xpath("//i[@class=\"fab fa-facebook-f\"]")).click();
        // Get the handles of all open windows
        Set<String> windowHandles = driver.getWindowHandles();
        // Iterate through the handles and switch to the new window
        for (String handle : windowHandles) {
            if (!handle.equals(currentWindow)) {
                driver.switchTo().window(handle);
            }
        }
        System.out.println(driver.getTitle());
        driver.switchTo().window(currentWindow);
        System.out.println(driver.getTitle());
    }
}
  • We have used the window handles and iterated in an advanced loop to be not equal to the current window.
  • Then switch to the new handle window popup.
  • We can see it got the titles of both pages after entering and exiting the popup.