DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk4 min

How to Handle JavaScript Alerts in Selenium WebDriver

Use Selenium’s Alert interface to read and handle native JavaScript alerts, confirmations, and prompts—with method examples for Java, Python, and JavaScript.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a browser-native JavaScript alert, confirm, or prompt in Selenium Java, switch to the alert with driver.switchTo().alert(). Use getText() to read its message, accept() to confirm, dismiss() to cancel, and—only for a prompt—sendKeys() to enter text before accepting.

Identify the kind of popup first

Selenium’s JavaScript alerts, prompts and confirmations documentation describes the three native popup messages JavaScript can show through the browser. Selenium’s Alert interface is for these browser-native dialogs, not page content.

  • Alert: Shows a message and an acknowledgement action. Read the message if needed, then accept or dismiss it.
  • Confirm: Asks the user to accept or cancel. Choose the result your test is meant to verify.
  • Prompt: Includes a text input. Enter a response, then accept, or dismiss to cancel without submitting text.

An HTML modal, banner, or custom overlay may look similar, but it is part of the webpage. Handle it as a page element rather than using Selenium’s Alert interface.

Handle a native alert in Java

The examples below use Selenium’s documented Java API. Obtain the alert after the page action that triggers it, then perform the operation appropriate to the dialog.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read the message and accept

Alert alert = driver.switchTo().alert();
String message = alert.getText();
alert.accept();

Make sure your test includes the imports and WebDriver setup appropriate to your project. getText() returns the dialog message; save or assert it before accepting if the message is part of the test.

Dismiss a confirmation

Alert confirm = driver.switchTo().alert();
String message = confirm.getText();
confirm.dismiss();

Use accept() for the positive choice and dismiss() for cancellation. The correct choice depends on the behavior under test.

Enter and submit a prompt response

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

Only a prompt has a text field. Selenium’s JavaScript API documents that attempting sendKeys on an alert or confirm dialog produces an error; do not use it as a general popup operation.

Equivalent operations in Python and JavaScript

The dialog behavior is the same across bindings, but method spelling and how the message is exposed differ.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Operation Java Python JavaScript
Get alert interface driver.switchTo().alert() Alert(driver) driver.switchTo().alert()
Read message alert.getText() alert.text alert.getText()
Accept alert.accept() alert.accept() alert.accept()
Dismiss alert.dismiss() alert.dismiss() alert.dismiss()
Enter prompt text alert.sendKeys("response") alert.send_keys("response") alert.sendKeys("response")

See Selenium’s official Java Alert interface, Python Alert API, and JavaScript Alert API for the binding-specific methods.

Timing and prompts that appear without handling

The alert must exist when Selenium switches to it. Perform the page action that triggers the dialog before calling driver.switchTo().alert(). The official alert guide does not provide a universal timing recipe for every late or absent alert, so avoid assuming a fixed delay will work across browsers and drivers.

Selenium’s current alert guide says recent drivers automatically dismiss beforeunload prompts by default. It points to the unhandledPromptBehavior setting for older behavior. Do not assume identical behavior across every browser and driver version; consult the documentation for the versions used in your test.

Rank #4
The Web Testing Handbook
  • Used Book in Good Condition

Troubleshoot common alert-handling failures

  • Selenium cannot switch to an alert: The dialog may not have appeared yet, or the popup may be an HTML element rather than a native JavaScript dialog. Confirm which kind of popup the page produced and call the alert switch after the triggering action.
  • sendKeys fails: The current dialog may be an alert or confirm, not a prompt. Only prompts accept response text.
  • The test took the wrong outcome: Check whether the scenario expects acceptance or cancellation. Use accept() for the positive action and dismiss() for cancellation.
  • A beforeunload prompt disappears automatically: Recent drivers dismiss these prompts by default according to Selenium’s alert guide. Review unhandledPromptBehavior and the relevant browser and driver documentation if the test requires different handling.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup:

Selenium is the right choice when you need to interact with a native JavaScript dialog. If you need a website screenshot instead, ScreenshotNeo provides a screenshot API and MCP server; it does not replace Selenium for accepting or dismissing alerts.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

One-call cURL example: 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, newsletter popups, and chat widgets are removed before the shot; each cleanup step can be turned off.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed. The response identifies the page verdict and billing status.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents and MCP clients.
  • The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 screenshots.

Sign up for 1,000 free screenshots a month, with no card required.

Frequently Asked Questions

How do I get alert text in Selenium WebDriver?

In Java, call driver.switchTo().alert().getText() after the native dialog appears.

Can Selenium enter text in an alert?

No. Enter text only in a prompt, using sendKeys in Java or JavaScript and send_keys in Python.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Does Selenium’s Alert API handle HTML modals?

No. It targets native JavaScript dialogs; handle an HTML modal as a webpage element.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.