How to Handle Confirm Dialog in Selenium: Simple Fix
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.
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();
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.
driver.findElement(By.id("confirmButton")).click(); Alert confirmAlert = driver.switchTo().alert(); confirmAlert.accept(); // Clicks OK on confirm dialog
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
WebDriverWaitwithExpectedConditions.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.