Skip to main content
SeleniumDecoded

UnhandledAlertException

UnhandledAlertException (Unexpected Alert Open): Causes and Fixes

Fix Selenium UnhandledAlertException (UnexpectedAlertPresentException in Python, UnexpectedAlertOpenError in JS): surprise alerts and prompt behaviour.

Common W3C: unexpected alert open Verified against Selenium 4.52.0
Exception name by language
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

// Java
org.openqa.selenium.UnhandledAlertException: unexpected alert open: {Alert text : Your session will expire in 2 minutes}
(Session info: chrome=131.0.6778.86)
# Python
selenium.common.exceptions.UnexpectedAlertPresentException: Alert Text: Your session will expire in 2 minutes
Message: 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

  1. Your action triggers a confirm dialog you did not handle. “Are you sure you want to delete?” after clicking Delete.
  2. A beforeunload prompt fires on navigation. You navigate away from a form with unsaved changes, or close the window.
  3. An unexpected application alert. Session timeout warnings, validation messages implemented as alert(), or debug alerts left in a test build.
  4. A timing race. The alert appears asynchronously after an XHR, between two of your commands.
  5. 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.

Wait for the dialog and handle it
Selenium 4 Stable
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.

Set the unhandled prompt behaviour
Selenium 4 Medium
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);
ValueWhat happens to the dialogError thrown?
dismiss and notify (default)DismissedYes
accept and notifyAcceptedYes
dismissDismissedNo
acceptAcceptedNo
ignoreLeft openYes, and it stays open

Warning: Silent accept or dismiss hides 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.

Go deeper