JavaScript Alerts

Three Kinds of Dialog

DialogCreated byButtonsShopEase example
alertalert("Item added")OK"Coupon applied"
confirmconfirm("Remove item?")OK / Cancelremoving an item from the cart
promptprompt("Enter gift message")text box + OK / Cancelgift wrap message

Note: These are browser dialogs, not HTML. You cannot locate them with findElement; switch to them with driver.switchTo().alert(). A popup made of <div> elements (a "modal") is normal HTML: use locators.

Handling Them

driver.findElement(By.cssSelector(".remove-item")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
System.out.println("Alert says: " + alert.getText());
alert.dismiss();          // Cancel: item stays in cart

driver.findElement(By.cssSelector(".remove-item")).click();
wait.until(ExpectedConditions.alertIsPresent()).accept();   // OK: item removed

driver.findElement(By.id("gift-message-btn")).click();
Alert prompt = wait.until(ExpectedConditions.alertIsPresent());
prompt.sendKeys("Happy Birthday!");
prompt.accept();

Example

Output:

Run CartAlertTest.main()

Example output

Alert says: Remove Nike Revolution 7 from your cart?

Forgetting the Alert

Example

If an alert is open and you call any other command, Selenium throws:

Run CartAlertTest.main()

Example output

org.openqa.selenium.UnhandledAlertException: unexpected alert open: {Alert text : Remove Nike Revolution 7 from your cart?}

Tip: Browser permission popups ("Allow notifications?") and the OS file dialog are not JavaScript alerts. Turn notifications off with ChromeOptions and upload files with sendKeys (see the Screenshots module).