JavaScript alerts are native browser dialogs. Use driver.switchTo().alert() to handle them.
Alert types:
| Type | Description |
|---|---|
alert() | Info message with OK button |
confirm() | Question with OK and Cancel |
prompt() | Input request with OK and Cancel |
Accept (click OK):
Java
Alert alert = driver.switchTo().alert();
System.out.println("Alert text: " + alert.getText());
alert.accept();
Dismiss (click Cancel):
Java
driver.switchTo().alert().dismiss();
Type into prompt:
Java
Alert prompt = driver.switchTo().alert();
prompt.sendKeys("My input text");
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();
alert.accept();
Common error:
NoAlertPresentException— alert has not appeared yet. Always useExpectedConditions.alertIsPresent()before switching.
