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”
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();
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());
The full source for this is in my Webdriver Java FAQs project:
If you want to learn how to use Selenium WebDriver with Java then check out our online courses.
You will need a Github account to comment. Or you can contact me with your comment.
I reserve the right to delete spam comments e.g. if your comment adds no value and its purpose is simply to create a backlink to another site offering training, or courses, etc.