0
0
Selenium-pythonDebug / FixBeginner · 3 min read

How to Handle Confirm Dialog in Selenium: Simple Fix

To handle a confirm dialog in Selenium, switch to the alert using driver.switchTo().alert() and then use accept() to click OK or dismiss() to click Cancel. This lets your test interact with the popup and continue smoothly.
🔍

Why This Happens

When a confirm dialog appears, Selenium cannot interact with the main page until the dialog is handled. If you try to click buttons or elements without switching to the alert, Selenium throws an error because the dialog blocks the page.

java
driver.findElement(By.id("confirmButton")).click();
// Trying to click OK without switching to alert
// This will cause an error
// driver.findElement(By.id("okButton")).click();
Output
org.openqa.selenium.UnhandledAlertException: unexpected alert open: {Alert text : Are you sure?}
🔧

The Fix

You must switch Selenium's focus to the confirm dialog using driver.switchTo().alert(). Then call accept() to press OK or dismiss() to press Cancel. This handles the popup and lets your test continue.

java
driver.findElement(By.id("confirmButton")).click();
Alert confirmAlert = driver.switchTo().alert();
confirmAlert.accept(); // Clicks OK on confirm dialog
Output
Test continues after clicking OK on confirm dialog without errors.
🛡️

Prevention

Always expect confirm dialogs when clicking buttons that trigger them. Use explicit waits to wait for the alert to appear before switching. Avoid interacting with page elements while an alert is open to prevent errors.

  • Use WebDriverWait with ExpectedConditions.alertIsPresent().
  • Handle alerts immediately after triggering actions that cause them.
  • Keep alert handling code clean and consistent.
⚠️

Related Errors

Other common alert-related errors include:

  • UnhandledAlertException: Happens if alert is not handled before interacting with the page.
  • NoAlertPresentException: Happens if you try to switch to an alert when none is present.

Quick fixes: always check alert presence before switching and handle alerts promptly.

Key Takeaways

Always switch to the alert before interacting with confirm dialogs using driver.switchTo().alert().
Use accept() to click OK and dismiss() to click Cancel on confirm dialogs.
Wait explicitly for alerts to appear before handling them to avoid timing issues.
Never try to interact with page elements while an alert is open to prevent errors.
Handle alerts immediately after triggering actions that cause them for smooth test flow.