Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
In Selenium Java, a browser prompt is a native JavaScript dialog, not an element in the page DOM. Trigger the action that opens it, wait for an alert, switch to it with driver.switchTo().alert(), read its text, optionally replace the prompt value with sendKeys(), and finish with accept() or dismiss().
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.alertIsPresent());
Alert prompt = driver.switchTo().alert();
String message = prompt.getText();
prompt.sendKeys("Selenium");
prompt.accept();
This sequence handles asynchronous prompts without racing the browser and keeps prompt logic separate from HTML-modal logic.
What Selenium calls a prompt
JavaScript exposes three common native popup types: alerts, confirms, and prompts. An alert displays a message and normally has only an OK action. A confirm offers positive and cancel actions. A prompt is similar to a confirm but also contains a text input. Selenium represents all three through the Alert interface.
Recommended Free Tools
A native popup is browser UI. It is not represented by a <div>, input, or button in the page’s DOM, so CSS and XPath locators cannot find it. The correct API is driver.switchTo().alert(). Once you have the Alert reference, use getText(), sendKeys(), accept(), and dismiss() as appropriate.
#1 Best Overall
Native prompt or HTML modal?
Before writing a locator, identify which kind of dialog the application created.
| Dialog | How it is implemented | Selenium approach | Typical failure when confused |
|---|---|---|---|
| Native alert, confirm, or prompt | JavaScript browser popup | switchTo().alert(), then use Alert |
NoAlertPresentException when no native dialog exists |
| HTML/CSS modal | Elements in the document | Locate with By; wait for visibility or clickability; use WebElement |
An alert switch fails, or a DOM locator cannot see browser UI |
For example, a page can display a custom overlay containing an input with a “Continue” button. That is an HTML modal even if it looks identical to a browser prompt. Conversely, JavaScript window.prompt() creates a native prompt that has no usable CSS selector.
The reliable Java workflow
- Trigger the dialog. Click a control or execute the script that opens the prompt.
- Wait for presence. Use
ExpectedConditions.alertIsPresent()instead of assuming the dialog appears immediately. - Switch once. Store the returned
Alertreference. - Read before changing state. Call
getText()while the dialog is open. - Enter a value when needed. Call
sendKeys()only on a prompt. - Choose the outcome. Use
accept()to submit or confirm, anddismiss()to cancel. - Continue in the correct context. Restore the required frame or window before locating page elements.
Complete prompt example
import java.time.Duration;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class PromptExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
try {
driver.get("https://example.test/prompt");
driver.findElement(By.id("open-prompt")).click();
Alert prompt = wait.until(ExpectedConditions.alertIsPresent());
String message = prompt.getText();
System.out.println("Prompt message: " + message);
prompt.sendKeys("Selenium");
prompt.accept();
// Continue with normal DOM operations after the prompt closes.
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("result")));
} finally {
driver.quit();
}
}
}
Replace the example URL and element IDs with those from your application. The explicit wait has a ten-second timeout; choose a limit that matches the slowest legitimate response in your environment rather than adding an arbitrary sleep.
Reading, entering, accepting, and dismissing
Read the message
prompt.getText() returns the visible message supplied by the page. Capture it before accepting or dismissing, because closing the dialog ends the context in which the text can be read.
Replace the prompt input
prompt.sendKeys("value") enters text into a prompt. Selenium documents that this operation completely replaces the placeholder text; it does not append to the existing placeholder. This makes it suitable for tests that need an exact submitted value.
Rank #2
Submit or confirm
Call prompt.accept() for the positive path. For a prompt, this submits the current input value. For an alert, it closes the message; for a confirm, it chooses the affirmative action.
Cancel
Call prompt.dismiss() to cancel a prompt or choose the negative action on a confirm. An alert has no meaningful cancel branch, so accepting it is normally the only completion action.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteWaiting correctly for asynchronous prompts
A prompt may be created by delayed JavaScript, an AJAX callback, or an event handler that runs after your click command returns. Calling switchTo().alert() immediately can therefore raise NoAlertPresentException. The explicit wait polls until a native dialog exists or the timeout expires.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
Do not replace this synchronization with a fixed Thread.sleep() as your primary strategy. A sleep is either too short for a slow run or unnecessarily long for a fast one. If your test has already switched windows or frames, perform that switch before triggering the JavaScript, then wait for the alert in that browsing context.
Prompts opened inside frames
JavaScript executed by a document inside an iframe can open a native prompt. Switch into the frame before clicking the control that triggers it:
Rank #3
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement frame = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("payment-frame")));
driver.switchTo().frame(frame);
driver.findElement(By.id("ask-name")).click();
Alert prompt = wait.until(ExpectedConditions.alertIsPresent());
String text = prompt.getText();
prompt.sendKeys("Ada");
prompt.accept();
driver.switchTo().defaultContent();
// Locate top-level page elements here.
Nested frames require one switch for each level, using frame() or a frame element at each step. The alert itself is handled through driver.switchTo().alert(); there is no separate alert locator scoped to the iframe. After closing it, return to the frame that owns the next element, or call defaultContent() to return to the top-level document.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Handling multiple or sequential prompts
Some workflows display more than one native dialog. Finish the first prompt completely, then wait again for the next one. Keep each reference local so you do not accidentally reuse a closed dialog.
Alert first = wait.until(ExpectedConditions.alertIsPresent());
String firstMessage = first.getText();
first.sendKeys("first value");
first.accept();
Alert second = wait.until(ExpectedConditions.alertIsPresent());
String secondMessage = second.getText();
second.dismiss();
Waiting again matters because the second dialog may be created only after the first acceptance is processed. If the second prompt is conditional, assert the page state that should cause it before waiting, and give the wait a failure message in your test framework so the timeout explains which step failed.
Unexpected prompts and WebDriver policy
A prompt can appear while WebDriver is executing another command, such as navigation or script execution. WebDriver supports an unhandledPromptBehavior capability for these cases. Depending on the configured behavior, an unexpected dialog can be accepted, dismissed, surfaced as a notification, or ignored.
Use a configured policy as a safety net, not as a replacement for explicit handling when the test depends on the prompt’s message or input. An automatic accept can hide a regression in which the wrong dialog appeared; an automatic dismiss can silently take a destructive cancel path. Keep the policy documented in driver setup and use the explicit wait-and-assert sequence for business-critical prompts.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Rank #4
Assertions that make prompt tests useful
Do more than prove that a dialog existed. Assert the message before acting, then verify the page state after the dialog closes.
Alert prompt = wait.until(ExpectedConditions.alertIsPresent());
String actual = prompt.getText();
if (!actual.equals("Enter your project name")) {
prompt.dismiss();
throw new AssertionError("Unexpected prompt text: " + actual);
}
prompt.sendKeys("Website refresh");
prompt.accept();
String result = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("result"))
).getText();
if (!result.contains("Website refresh")) {
throw new AssertionError("Submitted value was not applied");
}
Checking both the message and the resulting DOM state catches wrong-dialog, stale-workflow, and failed-submission defects that a simple accept() call would miss.
Common failures and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
NoAlertPresentException |
The dialog has not appeared, was already closed, or is an HTML modal. | Trigger the action first, wait with alertIsPresent(), and verify the dialog type. |
| Timeout waiting for alert | The trigger did not run, a locator hit the wrong element, or application logic suppressed the prompt. | Assert the trigger element is clickable, inspect page state, and confirm the prompt condition. |
sendKeys() fails |
The dialog is an alert or confirm, not a prompt, or the dialog closed. | Use sendKeys() only when a text input is present; reacquire the alert after a new prompt appears. |
| DOM locator cannot find the popup | You are trying to locate native browser UI with CSS or XPath. | Switch to the alert API. Use DOM locators only for an HTML modal. |
| Next element cannot be found after handling | The driver remains in an iframe or non-default window. | Switch back to the intended frame or window, or call defaultContent(). |
| Test accepts the wrong dialog | Automatic unhandled-prompt behavior hides an unexpected popup. | Use explicit handling, assert getText(), and review the configured capability. |
Performance and reliability practices
- Create one suitably scoped
WebDriverWaitand reuse it rather than adding sleeps throughout the test. - Keep the prompt interaction short: capture text, enter the required value, and close the dialog before doing unrelated work.
- Use deterministic test data so the submitted value and resulting page state can be asserted exactly.
- Close unexpected prompts during failure cleanup only if doing so cannot hide the original failure; preserve the original exception in your test report.
- When a prompt is opened from a frame, record the frame path in the test’s setup and restore it explicitly afterward.
- Configure an unhandled-prompt policy deliberately for your driver and document why that policy is safe for the suite.
Or skip the browser setup
If your goal is to capture the resulting page rather than exercise prompt behavior, ScreenshotNeo provides a website screenshot API and MCP server. It accepts a cookie or consent banner before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response identifies the result with X-Page-Verdict and X-Billed headers.
After your Selenium flow has produced the URL you want to inspect, one GET request returns PNG, JPEG, WebP, or a PDF. See the ScreenshotNeo documentation for all options.
Free tools Windows power users keep installed
One-click scans. No signup required.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo also offers an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Its plans include 1,000 screenshots per month free with no card; paid plans start at $5 for 3,000 screenshots. Create a free ScreenshotNeo account.
FAQ
Can Selenium type into a native prompt with a locator?
No. Native prompts are outside the DOM. Switch to the Alert interface and call sendKeys().
Best Value
Should I call getText() after accepting?
No. Read and store the message before accept() or dismiss() closes the dialog.
Does an iframe require a different alert API?
No. Enter the iframe before triggering the script, handle the native dialog with switchTo().alert(), then restore the required frame context.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →When should I use an unhandled-prompt policy?
Use it as a defined fallback for dialogs that appear during another command. If the prompt’s text or choice is part of the test’s expected behavior, handle it explicitly and assert its message.
Frequently Asked Questions
Can Selenium type into a native prompt with a locator?
No. Native prompts are outside the DOM. Switch to the Alert interface and call sendKeys().
Should I call getText() after accepting?
No. Read and store the message before accept() or dismiss() closes the dialog.
Does an iframe require a different alert API?
No. Enter the iframe before triggering the script, handle the native dialog with switchTo().alert(), then restore the required frame context.
When should I use an unhandled-prompt policy?
Use it as a fallback for dialogs that appear during another command. Handle prompts explicitly when their text or choice is part of the expected test behavior.
Quick Recap
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.

