Answer
Handling Random/Unexpected Alerts in Selenium
Some applications show alerts randomly — cookie consent banners, session warnings, or promotional pop-ups. These break tests if not handled.
Dismiss Alert If Present (Try-Catch Pattern)
Java
public void dismissAlertIfPresent() {
try {
Alert alert = driver.switchTo().alert();
System.out.println("Alert text: " + alert.getText());
alert.dismiss(); // or alert.accept()
} catch (NoAlertPresentException e) {
// No alert — that''s fine, continue
}
}
// Call before any critical action
dismissAlertIfPresent();
driver.findElement(By.id("checkoutBtn")).click();
Wait for Alert and Handle
Java
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
try {
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.accept();
} catch (TimeoutException e) {
// No alert appeared within 5 seconds
}
Handle CSS/Modal Pop-ups (Not JS Alerts)
Java
// Check if modal is visible and close it
try {
WebElement closeBtn = driver.findElement(By.cssSelector(".modal .close-btn"));
if (closeBtn.isDisplayed()) {
closeBtn.click();
}
} catch (NoSuchElementException e) {
// Modal not present
}
TestNG Listener — Handle Alerts on Every Failure
Java
@Override
public void onTestFailure(ITestResult result) {
try {
driver.switchTo().alert().dismiss();
} catch (NoAlertPresentException ignored) {}
// Then take screenshot
}
Types of Pop-ups and How to Handle
| Pop-up Type | Selenium Approach |
|---|---|
JS alert() | driver.switchTo().alert().accept() |
JS confirm() | .accept() or .dismiss() |
JS prompt() | .sendKeys("text") then .accept() |
| CSS Modal | Find and click close button |
| Browser auth dialog | Pass credentials in URL |
| Cookie banner | Click "Accept" button |
