Careeroza
JavaScript Alerts
Three Kinds of Dialog
| Dialog | Created by | Buttons | ShopEase example |
|---|---|---|---|
| alert | alert("Item added") | OK | "Coupon applied" |
| confirm | confirm("Remove item?") | OK / Cancel | removing an item from the cart |
| prompt | prompt("Enter gift message") | text box + OK / Cancel | gift 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).