Back to All Scenarios
Scenario 35 of 100
Popups & Windows
Advanced
JavaScript Alert Appears After Unpredictable Delay
β°Scenario Overview
JavaScript Alert Appears After Unpredictable Delay
Key Takeaways & Cheat Sheet
- βAvoid fragile hardcoded sleeps that slow down test execution
- βUtilize WebDriverWait to monitor browser alert status
- βUse ExpectedConditions.alertIsPresent() to synchronize dynamically
- βCatch UnhandledAlertException dynamically to capture delayed popups
Short Direct Answer
When alerts are triggered by slow background threads or asynchronous APIs, they render at unpredictable times. The professional solution is to leverage `WebDriverWait` with the `ExpectedConditions.alertIsPresent()` condition. This polls the browser continually and triggers the switch the moment the alert appears.
β οΈ Senior Warning (Red Flag)
Never write arbitrary sleeps (e.g. Thread.sleep(5000)) to wait for delayed alerts. If the server is fast, you waste 5 seconds; if the server is slow, the test fails anyway.
π‘ STAR Deep Dive Explanation & Pro Tip
This dynamic polling approach ensures that tests continue immediately as soon as the dialog pops up, preventing unnecessary execution lag.
SeleniumAutomation.java
Selenium 4 + Java// β
Monitor alert presence dynamically with a 15-second timeout
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
try {
// Polls DOM; returns Alert instance immediately when visible
Alert delayedAlert = wait.until(ExpectedConditions.alertIsPresent());
System.out.println("Alert message resolved: " + delayedAlert.getText());
delayedAlert.accept();
} catch (TimeoutException e) {
System.out.println("Alert did not appear within 15 seconds.");
}