Selenium WebDriver core API for automating web browsers across different platforms and programming languages.
—
Interface for interacting with JavaScript alert, confirm, and prompt dialogs, providing methods to accept, dismiss, read text, and input data.
Interface for interacting with JavaScript alert, confirm, and prompt dialogs.
/**
* Alert interface for JavaScript dialog interaction
* Handles alert(), confirm(), and prompt() dialogs
*/
interface Alert {
/**
* Dismiss the alert (click Cancel/No/Dismiss button)
* Equivalent to pressing ESC key or clicking Cancel
*/
void dismiss();
/**
* Accept the alert (click OK/Yes/Accept button)
* Equivalent to pressing ENTER key or clicking OK
*/
void accept();
/**
* Get the text content of the alert dialog
* @return Alert message text
*/
String getText();
/**
* Send keys to prompt dialog input field
* Only applicable for prompt() dialogs with text input
* @param keysToSend - Text to enter in prompt input field
*/
void sendKeys(String keysToSend);
}import org.openqa.selenium.WebDriver;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.time.Duration;
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
try {
driver.get("https://example.com/alerts");
// Trigger alert and handle it
driver.findElement(By.id("alert-button")).click();
// Wait for alert to appear
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
// Get alert text
String alertText = alert.getText();
System.out.println("Alert message: " + alertText);
// Accept the alert
alert.accept();
} finally {
driver.quit();
}// Simple alert dialog
public void handleSimpleAlert() {
driver.findElement(By.id("simple-alert")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
System.out.println("Alert says: " + alert.getText());
alert.accept(); // Only option is to accept
}
// Confirmation dialog (OK/Cancel)
public boolean handleConfirmDialog(boolean acceptDialog) {
driver.findElement(By.id("confirm-button")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
System.out.println("Confirm dialog: " + message);
if (acceptDialog) {
alert.accept(); // Click OK
return true;
} else {
alert.dismiss(); // Click Cancel
return false;
}
}
// Prompt dialog (input field with OK/Cancel)
public String handlePromptDialog(String inputText) {
driver.findElement(By.id("prompt-button")).click();
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String promptMessage = alert.getText();
System.out.println("Prompt message: " + promptMessage);
if (inputText != null) {
alert.sendKeys(inputText); // Enter text in prompt
alert.accept(); // Click OK
return inputText;
} else {
alert.dismiss(); // Click Cancel
return null;
}
}// Safe alert handling with error checking
public boolean handleAlertSafely(Duration timeout, boolean accept) {
try {
WebDriverWait alertWait = new WebDriverWait(driver, timeout);
Alert alert = alertWait.until(ExpectedConditions.alertIsPresent());
String alertText = alert.getText();
System.out.println("Alert detected: " + alertText);
if (accept) {
alert.accept();
} else {
alert.dismiss();
}
return true;
} catch (TimeoutException e) {
System.err.println("No alert appeared within " + timeout.getSeconds() + " seconds");
return false;
} catch (NoAlertPresentException e) {
System.err.println("Alert disappeared before it could be handled");
return false;
}
}
// Check if alert is present without waiting
public boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
// Handle alert with text validation
public boolean handleAlertWithValidation(String expectedText, boolean accept) {
try {
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String actualText = alert.getText();
if (expectedText.equals(actualText)) {
System.out.println("Alert text matches expected: " + actualText);
if (accept) {
alert.accept();
} else {
alert.dismiss();
}
return true;
} else {
System.err.println("Alert text mismatch. Expected: '" + expectedText + "', Actual: '" + actualText + "'");
alert.dismiss(); // Dismiss unexpected alert
return false;
}
} catch (TimeoutException e) {
System.err.println("Expected alert did not appear");
return false;
}
}// Form validation alert handling
public void testFormValidation() {
// Fill form with invalid data
driver.findElement(By.id("email")).sendKeys("invalid-email");
driver.findElement(By.id("submit")).click();
// Handle validation alert
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String validationMessage = alert.getText();
// Verify validation message
assertTrue("Validation message should contain 'email'",
validationMessage.toLowerCase().contains("email"));
alert.accept();
}
// Deletion confirmation
public void testDeleteConfirmation() {
// Click delete button
driver.findElement(By.className("delete-button")).click();
// Handle confirmation dialog
Alert confirmAlert = wait.until(ExpectedConditions.alertIsPresent());
String confirmText = confirmAlert.getText();
// Verify confirmation message
assertTrue("Confirmation should ask about deletion",
confirmText.toLowerCase().contains("delete"));
// Confirm deletion
confirmAlert.accept();
// Verify item was deleted (implementation specific)
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("deleted-item")));
}
// User input through prompt
public void testUserInputPrompt() {
String userInput = "Test User Name";
// Trigger prompt
driver.findElement(By.id("name-prompt")).click();
// Handle prompt dialog
Alert prompt = wait.until(ExpectedConditions.alertIsPresent());
System.out.println("Prompt: " + prompt.getText());
// Enter user input
prompt.sendKeys(userInput);
prompt.accept();
// Verify input was processed
WebElement result = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("user-name")));
assertEquals("User name should match input", userInput, result.getText());
}// Handle sequence of alerts
public void handleAlertSequence() {
driver.findElement(By.id("multiple-alerts")).click();
// First alert
Alert alert1 = wait.until(ExpectedConditions.alertIsPresent());
System.out.println("First alert: " + alert1.getText());
alert1.accept();
// Second alert
Alert alert2 = wait.until(ExpectedConditions.alertIsPresent());
System.out.println("Second alert: " + alert2.getText());
alert2.accept();
// Third alert (prompt)
Alert alert3 = wait.until(ExpectedConditions.alertIsPresent());
System.out.println("Third alert (prompt): " + alert3.getText());
alert3.sendKeys("Final input");
alert3.accept();
}
// Handle unexpected alerts during test
public void performActionWithAlertHandling(Runnable action) {
try {
action.run();
} catch (UnhandledAlertException e) {
System.out.println("Unexpected alert appeared: " + e.getAlertText());
// Handle the unexpected alert
Alert alert = driver.switchTo().alert();
alert.dismiss();
// Retry the action
action.run();
}
}
// Usage
performActionWithAlertHandling(() -> {
driver.findElement(By.id("risky-button")).click();
driver.findElement(By.id("next-step")).click();
});// Utility class for alert operations
public class AlertHelper {
private final WebDriver driver;
private final WebDriverWait wait;
public AlertHelper(WebDriver driver, Duration timeout) {
this.driver = driver;
this.wait = new WebDriverWait(driver, timeout);
}
public String getAlertText() {
try {
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
return alert.getText();
} catch (TimeoutException e) {
return null;
}
}
public boolean acceptAlert() {
try {
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.accept();
return true;
} catch (TimeoutException e) {
return false;
}
}
public boolean dismissAlert() {
try {
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.dismiss();
return true;
} catch (TimeoutException e) {
return false;
}
}
public boolean sendKeysToAlert(String text) {
try {
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.sendKeys(text);
alert.accept();
return true;
} catch (TimeoutException e) {
return false;
}
}
public AlertAction waitForAlert() {
try {
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
return new AlertAction(alert);
} catch (TimeoutException e) {
return null;
}
}
// Fluent interface for alert actions
public static class AlertAction {
private final Alert alert;
public AlertAction(Alert alert) {
this.alert = alert;
}
public AlertAction validateText(String expectedText) {
String actualText = alert.getText();
if (!expectedText.equals(actualText)) {
throw new AssertionError("Alert text mismatch. Expected: '" + expectedText + "', Actual: '" + actualText + "'");
}
return this;
}
public AlertAction validateTextContains(String partialText) {
String actualText = alert.getText();
if (!actualText.contains(partialText)) {
throw new AssertionError("Alert text does not contain: '" + partialText + "'. Actual: '" + actualText + "'");
}
return this;
}
public AlertAction sendKeys(String text) {
alert.sendKeys(text);
return this;
}
public void accept() {
alert.accept();
}
public void dismiss() {
alert.dismiss();
}
public String getText() {
return alert.getText();
}
}
}
// Usage of utility class
AlertHelper alertHelper = new AlertHelper(driver, Duration.ofSeconds(5));
// Simple alert handling
String alertText = alertHelper.getAlertText();
boolean alertHandled = alertHelper.acceptAlert();
// Fluent alert handling
alertHelper.waitForAlert()
.validateTextContains("Are you sure")
.accept();
// Prompt handling
alertHelper.waitForAlert()
.validateText("Please enter your name:")
.sendKeys("John Doe");// Comprehensive alert handling strategy
public class RobustAlertHandler {
private final WebDriver driver;
private final Duration defaultTimeout;
public RobustAlertHandler(WebDriver driver) {
this.driver = driver;
this.defaultTimeout = Duration.ofSeconds(10);
}
// Handle any type of alert with logging
public AlertResult handleAnyAlert(AlertStrategy strategy) {
try {
WebDriverWait wait = new WebDriverWait(driver, defaultTimeout);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String alertText = alert.getText();
System.out.println("Alert detected: " + alertText);
AlertResult result = new AlertResult(true, alertText);
switch (strategy) {
case ACCEPT:
alert.accept();
result.setAction("accepted");
break;
case DISMISS:
alert.dismiss();
result.setAction("dismissed");
break;
case ACCEPT_WITH_INPUT:
if (strategy.getInputText() != null) {
alert.sendKeys(strategy.getInputText());
}
alert.accept();
result.setAction("accepted with input: " + strategy.getInputText());
break;
}
return result;
} catch (TimeoutException e) {
System.out.println("No alert appeared within timeout");
return new AlertResult(false, null);
} catch (Exception e) {
System.err.println("Error handling alert: " + e.getMessage());
return new AlertResult(false, null);
}
}
enum AlertStrategy {
ACCEPT, DISMISS, ACCEPT_WITH_INPUT;
private String inputText;
public AlertStrategy withInput(String text) {
this.inputText = text;
return this;
}
public String getInputText() {
return inputText;
}
}
static class AlertResult {
private final boolean alertPresent;
private final String alertText;
private String action;
public AlertResult(boolean alertPresent, String alertText) {
this.alertPresent = alertPresent;
this.alertText = alertText;
}
// Getters and setters
public boolean isAlertPresent() { return alertPresent; }
public String getAlertText() { return alertText; }
public String getAction() { return action; }
public void setAction(String action) { this.action = action; }
}
}
// Usage
RobustAlertHandler alertHandler = new RobustAlertHandler(driver);
// Handle confirmation
AlertResult result = alertHandler.handleAnyAlert(AlertStrategy.ACCEPT);
if (result.isAlertPresent()) {
System.out.println("Alert was " + result.getAction() + ": " + result.getAlertText());
}
// Handle prompt with input
AlertResult promptResult = alertHandler.handleAnyAlert(
AlertStrategy.ACCEPT_WITH_INPUT.withInput("Test Input")
);Install with Tessl CLI
npx tessl i tessl/maven-org-seleniumhq-selenium--selenium-api