Skip to main content
blog title image

2 minute read - Selenium WebDriver FAQs Test Automation

Why Does Selenium Not Work With This Alert?

Jul 1, 2020

Q: “Why does Selenium not work with my Alert?” or “Why can’t Selenium handle the alert in my application?”

A: “Because the thing you think is an alert, is not an alert”

The use of the web has changed. HTML has changed. We can now style div elements to look like dialogs and alerts, we can even give them focus and make them modal. That doesn’t mean they fit the definition of an Alert. i.e. something triggered by the JavaScript methods: alert, confirm or prompt

Alerts

You can experiment with alerts on this page.

Click the buttons to trigger different types of alerts.

With any of the above examples, try and “inspect element” on the alert when it appears. You can’t. Because it is an alert.

WebDriver can handle these by switching to them and dismissing them.

    driver.get("https://testpages.herokuapp.com/styled/" + 
                "alerts/alert-test.html");
    driver.findElement(By.id("alertexamples")).click();
    driver.switchTo().alert().dismiss();

Not Alerts

The following examples are not alerts:

And here are some other examples which are beyond my CSS skills.

For each of the above, try and “inspect element” and you can. Because it is an HTML div, not an alert.

Examples of pseudo-alerts include:

  • those horrible “welcome to our website for the first time will you take our survey about our web site” dialogs
  • “you need to be logged in to see this content” overlays
  • “sign up for my mailing list and I’ll let you see what you came here for” overlay
  • “tweet this and then I’ll let you read it” overlay

Only use the Alert API on things that are Alerts. If you are using the Alert API, and it isn’t working, then the thing you are testing probably isn’t an an Alert.

    driver.get("https://testpages.herokuapp.com/styled/alerts/" +
                "fake-alert-test.html");
    driver.findElement(By.id("fakealert")).click();

    new WebDriverWait(driver, 10).until(
            ExpectedConditions.visibilityOfElementLocated(
                By.id("dialog")));

    // the div is not an alert
    Assertions.assertThrows(NoAlertPresentException.class,
            ()-> driver.switchTo().alert());

Full Source

The full source for this is in my Webdriver Java FAQs project:

Specifically:

If you want to learn how to use Selenium WebDriver with Java then check out our online courses.