JavaScript Alerts Live Outside the DOM
A JavaScript alert(), confirm(), or prompt() dialog is rendered by the browser chrome itself, not by the page's DOM, so none of Selenium's normal locator strategies (findElement, By.id, By.cssSelector) can see or interact with it. Instead, Selenium exposes driver.switchTo().alert(), which returns an Alert object representing whatever native dialog is currently open. Attempting to call any DOM-based command, or even a simple driver.getTitle(), while an unhandled alert is blocking the page will throw an UnhandledAlertException on some driver/browser combinations, because the alert freezes JavaScript execution on that page until it is dismissed.
Cricket analogy: A rain delay stops play entirely until the umpires inspect conditions, and nothing else on the field proceeds until that decision is made; a JS alert similarly blocks all page JavaScript until Selenium switches to and resolves it.
Accepting, Dismissing, and Reading Alert Text
The Alert interface offers four methods: accept() clicks the equivalent of OK, dismiss() clicks Cancel (or closes it, for a plain alert()), getText() reads the dialog's message, and sendKeys() types into a prompt()'s input field before accepting. A common pattern is to assert on getText() to verify the correct warning fired, then call accept() or dismiss() depending on the test scenario; for a window.confirm() used to confirm a delete action, calling dismiss() lets you test the 'cancel the delete' path without ever calling accept().
Cricket analogy: An umpire's decision review shows the replay text on the big screen before the third umpire confirms or overturns the on-field call; getText() reads the alert's message the same way before accept() or dismiss() acts on it.
WebDriver driver = new ChromeDriver();
driver.get("https://example.com/delete-account");
driver.findElement(By.id("delete-btn")).click();
// Wait for the native dialog and switch context to it
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
String message = alert.getText();
System.out.println("Confirm dialog says: " + message);
if (message.contains("permanently")) {
alert.dismiss(); // cancel the destructive action
} else {
alert.accept();
}
// Handling a window.prompt()
driver.findElement(By.id("rename-btn")).click();
Alert prompt = wait.until(ExpectedConditions.alertIsPresent());
prompt.sendKeys("New Project Name");
prompt.accept();
Never call driver.findElement() or any other DOM-based command while a native alert is open — most drivers throw UnhandledAlertException because the alert blocks the renderer. Always wait with ExpectedConditions.alertIsPresent() and switch to it first.
Custom (Non-Native) Popups and Unexpected Alert Handling
Many 'popups' in modern apps — cookie-consent banners, newsletter modals, styled confirmation dialogs — are not native browser alerts at all but ordinary <div> overlays built with CSS and JavaScript, meaning Alert/switchTo().alert() does not apply to them; they must be located and closed with regular findElement().click() calls like any other DOM element, and you should check for their presence defensively since they often appear only on the first page load or after a delay. For genuine native alerts that might appear unpredictably (e.g., a 'leave site?' beforeunload prompt), configure the driver's unexpected alert behavior via UnexpectedAlertBehaviour (ACCEPT, DISMISS, IGNORE) in ChromeOptions so tests don't hang or fail unpredictably when an alert appears outside an explicitly scripted step.
Cricket analogy: Telling apart a genuine third-umpire review signal from a fielder's casual gesture takes practice; distinguishing a native alert() from a styled DOM modal takes the same discernment, since only one uses switchTo().alert().
In Selenium's ChromeOptions, set setUnexpectedAlertBehaviour(UnexpectedAlertBehaviour.ACCEPT) (or DISMISS) so that an unscripted native alert appearing mid-test is auto-handled instead of causing subsequent commands to throw or the test to hang indefinitely.
- Native JS alert(), confirm(), and prompt() dialogs render outside the DOM and require driver.switchTo().alert(), not findElement().
- The Alert interface provides accept(), dismiss(), getText(), and sendKeys() (for prompts) to interact with the dialog.
- Any DOM-based command issued while an alert is open typically throws UnhandledAlertException, so wait for and switch to the alert first.
- Use WebDriverWait with ExpectedConditions.alertIsPresent() rather than fixed sleeps, since alerts can appear after variable delays.
- Cookie banners and styled confirmation modals are usually plain DOM elements, not native alerts, and must be closed with regular click() calls.
- Configure ChromeOptions' UnexpectedAlertBehaviour to auto-accept or auto-dismiss alerts that can appear unpredictably outside a scripted step.
- sendKeys() on an Alert only works for window.prompt() dialogs that have a text input field.
Practice what you learned
1. Why can't driver.findElement(By.id("ok-button")) locate the OK button on a native JavaScript alert() dialog?
2. What is the effect of calling dismiss() on a window.confirm() dialog?
3. A test needs to close a cookie-consent banner that appears as a styled <div> overlay on page load. What is the correct approach?
4. Why should you use WebDriverWait with ExpectedConditions.alertIsPresent() instead of immediately calling driver.switchTo().alert()?
5. What does configuring UnexpectedAlertBehaviour.ACCEPT in ChromeOptions accomplish?
Was this page helpful?
You May Also Like
Working with Frames and Multiple Windows
Learn how to switch WebDriver's context into iframes and nested frames, and how to detect, switch between, and close multiple browser windows and tabs.
JavaScriptExecutor for Tricky Elements
Learn how JavascriptExecutor lets Selenium run arbitrary JavaScript to work around interactability limitations, and when relying on it can mask real bugs.
Actions Class: Mouse Hover and Drag-and-Drop
Learn how Selenium's Actions class composes mouse hover, click-and-hold, and multi-step drag gestures that simple click() and sendKeys() calls cannot express.