πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
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.");
}