Implementation:SeleniumHQ Selenium Alert
| Knowledge Sources | |
|---|---|
| Domains | WebDriver, Browser_Automation |
| Last Updated | 2026-02-12 00:00 GMT |
Overview
Concrete tool for interacting with browser JavaScript alert, confirm, and prompt dialogs provided by the Selenium WebDriver library.
Description
The Alert interface represents a browser dialog (alert, confirm, or prompt) and provides methods to accept or dismiss it, read its displayed text, and type into it (for prompt dialogs). It is the return type of WebDriver.TargetLocator.alert(), which switches focus to the currently active dialog.
Usage
Import Alert when you need to handle native browser dialogs triggered by JavaScript alert(), confirm(), or prompt() calls during automated browser interaction.
Code Reference
Source Location
- Repository: SeleniumHQ_Selenium
- File: java/src/org/openqa/selenium/Alert.java
Signature
public interface Alert {
void dismiss();
void accept();
String getText();
void sendKeys(String keysToSend);
}
Import
import org.openqa.selenium.Alert;
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| keysToSend | String | Yes (for sendKeys) | The text to type into a prompt dialog's input field. |
Outputs
| Name | Type | Description |
|---|---|---|
| getText result | String | The text message currently displayed in the alert, confirm, or prompt dialog. |
| dismiss | void | Dismisses the dialog (equivalent to clicking "Cancel" on a confirm/prompt, or closing an alert). |
| accept | void | Accepts the dialog (equivalent to clicking "OK"). |
| sendKeys | void | Types the specified text into the prompt dialog input field. |
Usage Examples
import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
WebDriver driver = // ... obtain driver instance
// Trigger an alert via a button click
driver.findElement(By.id("alert-button")).click();
// Switch to the alert dialog
Alert alert = driver.switchTo().alert();
// Read the alert text
String alertText = alert.getText();
System.out.println("Alert says: " + alertText);
// Accept (click OK) the alert
alert.accept();
// Handle a confirm dialog by dismissing it (click Cancel)
driver.findElement(By.id("confirm-button")).click();
Alert confirm = driver.switchTo().alert();
confirm.dismiss();
// Handle a prompt dialog by typing text and accepting
driver.findElement(By.id("prompt-button")).click();
Alert prompt = driver.switchTo().alert();
prompt.sendKeys("Hello from Selenium");
prompt.accept();