๐ How to Handle Browser Pop-ups and Alerts in Selenium (Java)
Browser pop-ups and JavaScript alerts are common when working with web applications. Selenium provides a simple way to handle them using the Alert interface.
✅ Types of Browser Pop-ups
JavaScript Alerts / Confirms / Prompts
Authentication Pop-ups (username/password)
HTML-based modals or pop-ups
Selenium can only directly interact with JavaScript pop-ups (not OS-level pop-ups).
✅ 1. Handling JavaScript Alerts in Selenium (Java)
๐จ Example: Alert
java
Copy
Edit
// Switch to the alert
Alert alert = driver.switchTo().alert();
// Accept the alert
alert.accept();
๐จ Example: Confirm Box
java
Copy
Edit
Alert alert = driver.switchTo().alert();
// Dismiss the alert (click Cancel)
alert.dismiss();
๐จ Example: Prompt Box
java
Copy
Edit
Alert alert = driver.switchTo().alert();
// Send text to the prompt
alert.sendKeys("Some input");
// Accept the prompt
alert.accept();
✅ Complete Example:
java
Copy
Edit
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class AlertHandlingExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/alert-demo");
// Trigger the alert
driver.findElement(By.id("alertButton")).click();
// Switch and accept the alert
Alert alert = driver.switchTo().alert();
System.out.println("Alert text: " + alert.getText());
alert.accept();
driver.quit();
}
}
✅ 2. Handling Authentication Pop-ups (Basic Auth)
Selenium cannot handle browser-based authentication pop-ups directly, but a workaround is to pass credentials in the URL:
java
Copy
Edit
driver.get("https://username:password@yourwebsite.com");
⚠️ Only works with HTTP Basic Auth (not custom login dialogs).
✅ 3. Handling HTML-Based Pop-ups
If the pop-up is HTML (not a real browser alert), treat it like any other web element:
java
Copy
Edit
driver.findElement(By.className("modal-close")).click();
⏱️ Optional: Wait for Alert to Appear
Sometimes the alert doesn't appear immediately:
java
Copy
Edit
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.accept();
๐ง Summary
Type of Pop-up Handling Method
JavaScript Alert/Prompt driver.switchTo().alert()
Authentication Pop-up Use URL with credentials
HTML Modal or Dialog Locate and interact like normal element
Learn Selenium JAVA Training in Hyderabad
Visit Our Quality Thought Training in Hyderabad
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments