Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:SeleniumHQ Selenium Alert

From Leeroopedia
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

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();

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment