Why Selenium Might Not Handle Your "Alert"
Kushal Parikh
QA Automation Engineer | SDET | Test Automation Consultant | Selenium | Java | Playwright | SFPC? Certified | Driving Quality Through Automation
Selenium handles real alerts (triggered by JavaScript methods like alert(), confirm(), or prompt()) and Fake-alerts (HTML elements styled to look like alerts) differently.
1. Handling Real Alerts
Real alerts are system-level pop-ups. You can’t inspect them in the browser, but Selenium can interact with them using the Alert API.
Code:
// Navigate to a real alert
driver.get("https://testpages.herokuapp.com/styled/alerts/alert-test.html");
// Trigger and dismiss the alert
driver.findElement(By.id("alertexamples")).click();
driver.switchTo().alert().accept();
2. Handling Fake-Alerts
Pseudo-alerts are just HTML elements, like <div> tags, styled to look like alerts. You can inspect and interact with them like regular web elements.
Code:
// Navigate to a pseudo-alert/fake-alert (HTML div)
driver.get("https://testpages.herokuapp.com/styled/alerts/fake-alert-test.html");
// Trigger the pseudo-alert
driver.findElement(By.id("fakealert")).click();
// Wait for the pseudo-alert to appear and close it
new WebDriverWait(driver, Duration.ofSeconds(10)).until(
ExpectedConditions.visibilityOfElementLocated(By.id("dialog")));
driver.findElement(By.id("dialog-ok")).click();
Examples of pseudo-alerts include:
Key Takeaway
Use Selenium’s Alert API for real alerts, and standard element interaction methods for pseudo-alerts.
Happy Testing !