To handle JavaScript alerts (alert, confirm, prompt), first switch to the alert and then use accept() or dismiss().
Accept (click OK):
Java
Alert alert = driver.switchTo().alert();
alert.accept();
Dismiss (click Cancel):
Java
Alert alert = driver.switchTo().alert();
alert.dismiss();
Get alert text:
Java
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
System.out.println("Alert message: " + alertText);
alert.accept();
Type into prompt alert:
Java
Alert prompt = driver.switchTo().alert();
prompt.sendKeys("My answer");
prompt.accept();
Wait for alert before switching:
Java
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
alert.accept();
Alert types:
| Type | Description | Method |
|---|---|---|
alert | Simple message + OK | accept() |
confirm | Question + OK + Cancel | accept() or dismiss() |
prompt | Input + OK + Cancel | sendKeys() then accept() |
Common error:
NoAlertPresentException— the alert has not appeared yet. Always useExpectedConditions.alertIsPresent()beforeswitchTo().alert().
