Selenium Alerts

What A JavaScript Alert Is

A JavaScript alert is a small popup box the browser generates, separate from the regular webpage. Regular locators like By.id cannot find elements inside an alert because it lives outside the normal HTML structure.

Diagram: Alert Sitting Outside The Page

[Browser Window]
   |
   |-- [Webpage HTML - findElement works here]
   |
   |-- [JavaScript Alert Box - switchTo().alert() works here]

Types Of Alerts

Simple Alert

Shows a message with a single OK button.

Confirmation Alert

Shows a message with OK and Cancel buttons, used for yes-or-no decisions like deleting an item.

Prompt Alert

Shows a message with a text input field along with OK and Cancel buttons.

Switching To An Alert

Selenium needs to switch its focus to the alert box before interacting with it.

Alert alert = driver.switchTo().alert();

Accepting An Alert

Clicking OK on an alert is called accepting it.

alert.accept();

Dismissing An Alert

Clicking Cancel on an alert is called dismissing it.

alert.dismiss();

Reading Alert Text

String alertMessage = alert.getText();
System.out.println(alertMessage);

This reads the message shown inside the alert, useful for confirming the correct warning appears.

Typing Into A Prompt Alert

alert.sendKeys("Selenium Student");
alert.accept();

This types a name into a prompt alert's text field and then clicks OK.

Complete Example: Handling A Delete Confirmation

driver.findElement(By.id("delete-account-btn")).click();
Alert confirmAlert = driver.switchTo().alert();
String message = confirmAlert.getText();
System.out.println("Alert says: " + message);
confirmAlert.accept();

This clicks a delete button, reads the warning message the browser shows, and confirms the deletion by accepting the alert.

Common Mistake

Trying to use findElement() on an alert throws a NoSuchElementException every time. Alerts always need switchTo().alert() first, never regular locator methods.

Handling Unexpected Alerts

Some pages trigger alerts unexpectedly during navigation, blocking further commands. Wrapping alert handling in a try-catch block prevents a script from crashing when an alert appears without warning.

try {
    Alert unexpectedAlert = driver.switchTo().alert();
    unexpectedAlert.dismiss();
} catch (NoAlertPresentException e) {
    System.out.println("No alert appeared.");
}

Leave a Comment

Your email address will not be published. Required fields are marked *