UnhandledAlertException
UnhandledAlertException (Unexpected Alert Open): Causes and Fixes
Fix Selenium UnhandledAlertException (UnexpectedAlertPresentException in Python, UnexpectedAlertOpenError in JS): surprise alerts and prompt behaviour.
| Java | org.openqa.selenium.UnhandledAlertException |
|---|---|
| Python | selenium.common.exceptions.UnexpectedAlertPresentException |
| JavaScript | UnexpectedAlertOpenError |
| C# | OpenQA.Selenium.UnhandledAlertException |
What the error means
A JavaScript dialog (alert, confirm, prompt, or a beforeunload “Leave site?” prompt) is open, and you sent a command that is not about the dialog. While a user prompt is open, the page is blocked, so the driver cannot run your command.
What happens next is controlled by the unhandled prompt behaviour capability. The W3C default is “dismiss and notify”: the driver dismisses the dialog and throws this error so you know it happened. That is why the alert is often gone by the time you look at the screenshot.
What it looks like
// Javaorg.openqa.selenium.UnhandledAlertException: unexpected alert open: {Alert text : Your session will expire in 2 minutes} (Session info: chrome=131.0.6778.86)# Pythonselenium.common.exceptions.UnexpectedAlertPresentException: Alert Text: Your session will expire in 2 minutesMessage: unexpected alert open: {Alert text : Your session will expire in 2 minutes}// JavaScript (selenium-webdriver)UnexpectedAlertOpenError: unexpected alert open: {Alert text : Your session will expire in 2 minutes}// C#OpenQA.Selenium.UnhandledAlertException : unexpected alert open: {Alert text : Your session will expire in 2 minutes}The alert text is included in the message (and exposed as a property on the exception in Java, Python and C#), which usually identifies the culprit immediately.
Common causes
- Your action triggers a confirm dialog you did not handle. “Are you sure you want to delete?” after clicking Delete.
- A
beforeunloadprompt fires on navigation. You navigate away from a form with unsaved changes, or close the window. - An unexpected application alert. Session timeout warnings, validation messages implemented as
alert(), or debug alerts left in a test build. - A timing race. The alert appears asynchronously after an XHR, between two of your commands.
- A previous test left a dialog open, typically when tests share a browser and one failed mid-flow.
How to fix it
Your action triggers a confirm dialog
Wait for the alert, read it if you want to assert on it, then accept or dismiss it before doing anything else.
driver.findElement(By.id("delete")).click();Alert alert = new WebDriverWait(driver, Duration.ofSeconds(5)) .until(ExpectedConditions.alertIsPresent());assertEquals("Are you sure you want to delete?", alert.getText());alert.accept();driver.find_element(By.ID, "delete").click()alert = WebDriverWait(driver, 5).until(EC.alert_is_present())assert alert.text == "Are you sure you want to delete?"alert.accept()await driver.findElement(By.id('delete')).click();await driver.wait(until.alertIsPresent(), 5000);const alert = await driver.switchTo().alert();assert.strictEqual(await alert.getText(), 'Are you sure you want to delete?');await alert.accept();driver.FindElement(By.Id("delete")).Click();IAlert alert = new WebDriverWait(driver, TimeSpan.FromSeconds(5)) .Until(d => { try { return d.SwitchTo().Alert(); } catch (NoAlertPresentException) { return null; } });Assert.That(alert.Text, Is.EqualTo("Are you sure you want to delete?"));alert.Accept();For a prompt, call sendKeys on the alert before accept. The alerts lesson covers all three dialog types.
A beforeunload prompt fires on navigation
Either complete or discard the form through the UI before navigating, or handle the “Leave site?” dialog as an alert immediately after the navigation command. In test environments it is often simplest to set the unhandled prompt behaviour to accept (next section) so these prompts never block teardown.
An unexpected application alert
If the alert is part of the product, the test should expect and handle it. If it is noise you never care about, configure the session to deal with it automatically.
ChromeOptions options = new ChromeOptions();options.setUnhandledPromptBehaviour(UnexpectedAlertBehaviour.ACCEPT);WebDriver driver = new ChromeDriver(options);options = webdriver.ChromeOptions()options.unhandled_prompt_behavior = "accept"driver = webdriver.Chrome(options=options)const chrome = require('selenium-webdriver/chrome');const options = new chrome.Options();options.setAlertBehavior('accept');const driver = await new Builder().forBrowser('chrome').setChromeOptions(options).build();var options = new ChromeOptions{ UnhandledPromptBehavior = UnhandledPromptBehavior.Accept};var driver = new ChromeDriver(options);| Value | What happens to the dialog | Error thrown? |
|---|---|---|
dismiss and notify (default) | Dismissed | Yes |
accept and notify | Accepted | Yes |
dismiss | Dismissed | No |
accept | Accepted | No |
ignore | Left open | Yes, and it stays open |
Warning: Silent
acceptordismisshides real behaviour. An auto-accepted “Delete everything?” confirm will happily delete everything. Use silent modes only for dialogs you have decided are irrelevant, and prefer the notify variants in most suites so you still see that something happened.
A timing race
When an alert may or may not appear (a session warning on slow runs), check for it with a short wait at the points where it can occur, and handle it if present. The handle unexpected alert recipe has a reusable helper. Catching the exception and retrying the command is also valid, because with the default behaviour the dialog has already been dismissed.
A previous test left a dialog open
Use a fresh browser per test, or at least make teardown robust: try to switch to an alert and dismiss it before navigating to the next test’s start page.
How to prevent it
- Handle every dialog your product shows as an explicit test step, including asserting on its text.
- Keep the default “notify” behaviours in most suites so surprise dialogs fail loudly.
- Ask developers to replace debug
alert()calls and session warnings in test builds with in-page UI, which is also easier to test. - Isolate tests in fresh sessions so one test’s dialog never leaks into the next.
Related errors
- NoSuchWindowException: a confirm that closed the window as a side effect.
- ElementClickInterceptedException: an in-page modal, not a native dialog, is in the way.
- JavascriptException: a script you ran failed because a dialog was blocking the page.
- TimeoutException: waiting for an alert that never appeared.
Go deeper
- Alerts and Popups Handle JavaScript alerts, confirms, prompts, and authentication dialogs.
- Browser Options & Configuration Learn how to configure browser options in Selenium WebDriver, including headless mode, window size, and custom arguments.
- Common Errors Diagnose and fix the most common Selenium errors and exceptions.