</>

Technology

Selenium

Difficulty

Beginner

Interview Question

How to handle alerts in Selenium?

Switch to an alert using driver.switchTo().alert() then use accept() to click OK or dismiss() to click Cancel.

Answer

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:

TypeDescriptionMethod
alertSimple message + OKaccept()
confirmQuestion + OK + Cancelaccept() or dismiss()
promptInput + OK + CancelsendKeys() then accept()

Common error: NoAlertPresentException — the alert has not appeared yet. Always use ExpectedConditions.alertIsPresent() before switchTo().alert().

Follow AutomateQA

Related Topics