</>

Technology

Selenium

Difficulty

Intermediate

Interview Question

How to handle alerts and popups in Selenium WebDriver?

Use driver.switchTo().alert() to interact with JavaScript alert, confirm, and prompt dialog boxes.

Answer

JavaScript alerts are native browser dialogs. Use driver.switchTo().alert() to handle them.

Alert types:

TypeDescription
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 use ExpectedConditions.alertIsPresent() before switching.

Follow AutomateQA

Related Topics