0
0
Selenium-pythonDebug / FixBeginner · 4 min read

How to Handle Prompt Dialogs in Selenium WebDriver

To handle a prompt dialog in Selenium, switch to the alert using driver.switchTo().alert(), then use sendKeys() to enter text and accept() to confirm. This lets you interact with the prompt box during automated tests.
🔍

Why This Happens

Prompt dialogs are special pop-up boxes that ask users to enter some text before continuing. If you try to interact with the main page without handling the prompt first, Selenium throws an error because the prompt blocks the page.

java
driver.findElement(By.id("showPromptButton")).click();
// Trying to send keys directly to the page element without handling prompt
WebElement input = driver.findElement(By.id("inputField"));
input.sendKeys("Test input");
Output
org.openqa.selenium.UnhandledAlertException: unexpected alert open: {Alert text : Please enter your name}
🔧

The Fix

You must switch Selenium's focus to the prompt alert before interacting with it. Use driver.switchTo().alert() to get the prompt, then sendKeys() to enter text, and finally accept() to close the prompt and continue.

java
driver.findElement(By.id("showPromptButton")).click();

// Switch to prompt alert
Alert prompt = driver.switchTo().alert();

// Enter text into prompt
prompt.sendKeys("Test input");

// Accept the prompt to close it
prompt.accept();
Output
Prompt accepted and test continues without error.
🛡️

Prevention

Always check if your test triggers a prompt dialog and handle it immediately using switchTo().alert(). Avoid trying to interact with page elements while a prompt is open. Use explicit waits if needed to wait for the prompt to appear before switching.

Best practices include:

  • Use try-catch blocks to handle unexpected alerts gracefully.
  • Keep prompt handling code close to the action that triggers it.
  • Use clear comments to mark alert handling steps.
⚠️

Related Errors

Other common alert-related errors include:

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

Quick fixes:

  • Always switch to alert before interacting.
  • Use explicit waits to ensure alert presence.
  • Catch exceptions to handle unexpected alerts.

Key Takeaways

Always switch to the prompt alert using driver.switchTo().alert() before interacting.
Use sendKeys() to enter text and accept() to close the prompt dialog.
Avoid interacting with page elements while a prompt is open to prevent errors.
Use explicit waits to handle timing issues with prompt dialogs.
Handle alert exceptions gracefully to keep tests stable.