ScreenshotNeo

BlogHow-to

How to Handle JavaScript Alerts in Selenium WebDriver

Use Selenium WebDriver to read, accept, dismiss, and answer native JavaScript alerts, confirms, and prompts in Java, with Python and JavaScript equivalents.

By the ScreenshotNeo team4 October 20266 min read

Selenium handles browser-native JavaScript alerts, confirmation dialogs, and prompts through its alert interface. In Java, switch to the open dialog with driver.switchTo().alert(); read its message with getText(); then call accept() or dismiss(). For a prompt, enter text with sendKeys() before accepting.

This guide covers native dialogs. An HTML modal, cookie banner, or page overlay is ordinary page content and must be handled with normal element locators and interactions instead.

1. Recognize the dialog type

Selenium’s documentation describes an API for the three types of native popup messages offered by JavaScript: alerts, prompts, and confirmations. They look like browser dialogs and block interaction with the page until handled. The Selenium alerts guide explains the distinction.

Type What it does Typical Selenium action
Alert Shows a message and an acknowledgement action. Read the text if needed, then accept or dismiss.
Confirm Asks the user to accept or cancel an action. Accept to confirm; dismiss to cancel.
Prompt Asks for a text response. Enter text, then accept; dismiss to cancel.

2. Handle an alert in Java

Use Selenium’s Java binding and a browser driver for the browser configured in your project. The example below assumes driver is an already-created WebDriver and the page action opens a native alert.

import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;

public class AlertExample {
    public static void handleAlert(WebDriver driver) {
        Alert alert = driver.switchTo().alert();
        String message = alert.getText();
        System.out.println("Alert text: " + message);
        alert.accept();
    }
}

getText() returns the dialog message. accept() chooses the affirmative action. If the test should cancel, use alert.dismiss() instead. Choose the expected outcome based on the test case, not on the dialog’s visual wording alone.

Handle a confirmation

Alert confirm = driver.switchTo().alert();
String message = confirm.getText();
confirm.dismiss(); // Cancel the action

Replace dismiss() with accept() when the test is meant to confirm the action. You can inspect the text before choosing either result.

Answer a prompt

Alert prompt = driver.switchTo().alert();
String question = prompt.getText();
prompt.sendKeys("response");
prompt.accept();

The prompt’s text field is the only one of these dialog types that accepts a response. To cancel the prompt, call dismiss() without entering a response.

3. Equivalent operations in Python and JavaScript

The operations are similar across bindings, though method names and access to the text differ. See the official Python Alert API and JavaScript Alert API.

Python

from selenium.webdriver.common.alert import Alert

# driver is an existing Selenium WebDriver and the dialog is already open.
alert = Alert(driver)
message = alert.text
print("Alert text:", message)
alert.accept()

# For a prompt:
prompt = Alert(driver)
prompt.send_keys("response")
prompt.accept()

# For a confirmation you want to cancel:
confirm = Alert(driver)
confirm.dismiss()

In Python, alert text is exposed as the .text property and the input method is spelled send_keys().

JavaScript

// driver is an existing Selenium WebDriver and the dialog is already open.
const alert = await driver.switchTo().alert();
const message = await alert.getText();
console.log("Alert text:", message);
await alert.accept();

// For a prompt:
const prompt = await driver.switchTo().alert();
await prompt.sendKeys("response");
await prompt.accept();

// For a confirmation you want to cancel:
const confirm = await driver.switchTo().alert();
await confirm.dismiss();

JavaScript uses the asynchronous WebDriver API, so await the alert operations. The JavaScript API reports an error if sendKeys() is called on an alert or confirmation rather than a prompt.

4. Wait for an alert before handling it

The alert must be open when Selenium switches to it. If the page action triggers the dialog asynchronously, attempting to switch immediately can fail because the dialog is not present yet. Use your binding’s explicit-wait facilities when the trigger and dialog opening are not immediate. Check the wait API for the Selenium binding and version used by your project; timing behavior can vary by driver and page.

For Java, Selenium’s alert condition can be used with WebDriverWait and ExpectedConditions.alertIsPresent():

import java.time.Duration;
import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

// Run the page action that triggers the alert before this wait.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
alert.accept();

Set the timeout to a limit appropriate for the test environment. A wait is a maximum period to look for the dialog, not a reason to add a large fixed sleep to every test. If the expected dialog does not appear before the limit, investigate whether the triggering action ran and whether the page opened a native dialog or a custom overlay.

5. Or skip the browser setup

If your task is to capture a website image or PDF rather than automate a dialog interaction, ScreenshotNeo is a website screenshot API and MCP server for developers. It does not operate Selenium alerts; it provides a direct capture request. See the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" \
  -d access_key=YOUR_API_KEY \
  --data-urlencode url=https://stripe.com \
  -o shot.webp

Cookie banners and consent overlays, newsletter popups, and chat widgets are handled before capture. Bot checks, blank pages, failed loads, timeouts, and cache hits are never billed. An MCP server lets AI agents such as Claude, Cursor, and other MCP clients take screenshots. The free plan includes 1,000 screenshots each month with no card; paid plans start at $5 for 3,000. Sign up for free and capture your first screenshots.

6. Troubleshooting

Symptom Likely cause What to do
Selenium cannot switch to an alert. No native dialog is open at that moment, or the page action did not trigger one. Verify the trigger and wait for the alert before switching. Confirm that the popup is browser-native rather than an HTML modal.
The alert text is empty or differs from the expected text. The test may be reading a different dialog, or the expected text may not match the page state. Read the text from the active alert immediately after switching and check the page’s triggering conditions.
sendKeys() fails. The active dialog is an alert or confirm, not a prompt. Use text input only for a prompt. For an alert or confirm, accept or dismiss it.
The prompt submits no response. The test did not enter text before accepting, or it dismissed the prompt. Call sendKeys() on the prompt before accept(), and verify the resulting page state.
A confirmation leads to the wrong result. The test chose the wrong branch. Use accept() for the affirmative branch and dismiss() for cancellation.
A beforeunload dialog disappears automatically. Recent drivers automatically dismiss these prompts by default. If the test needs older prompt handling behavior, review Selenium’s unhandledPromptBehavior setting and the documentation for the exact driver in use.
An alert-like popup is not found by the Alert API. It is likely page HTML styled to look like a dialog. Inspect the page structure and locate the overlay’s elements with ordinary WebDriver element methods.

7. Reliability, performance, and cost

  • Reliability: trigger the dialog through the same user action your test is validating, wait for it when necessary, and assert the expected text or resulting page behavior. Do not assume every browser and driver handles every prompt identically.
  • Performance: handle the dialog as soon as it appears so it does not block further browser interaction. Prefer a bounded explicit wait to an unconditional sleep.
  • Test isolation: accept or dismiss each expected dialog before continuing or ending the test. A leftover modal prompt can prevent later commands from reaching the page.
  • Cost: the Selenium alert operations do not require a screenshot service. If the separate goal is repeatable screenshot or PDF capture, ScreenshotNeo offers 1,000 free captures per month without a card, then paid plans from $5 for 3,000; all features are on every plan. Yearly billing gives two months free.

8. Frequently asked questions

How do I get alert text in Selenium WebDriver?

Switch to the open dialog, then call getText() in Java or JavaScript. In Python, read the .text property.

Can I type into a JavaScript alert?

No. The text-entry operation applies to a prompt. Alerts and confirmations do not have a prompt response field.

Does Selenium’s alert API handle HTML modals?

No. Use normal element locators and interactions for overlays that belong to the page DOM.

What does dismissing a prompt do?

It cancels the prompt instead of submitting the entered response.

References: Selenium: JavaScript alerts, prompts and confirmations; Java Alert API; Python Alert API; JavaScript Alert API.