Alerts and Popups
Handle JavaScript alerts, confirms, prompts, and authentication dialogs.
JavaScript alerts, confirm boxes, and prompts are modal dialogs that block page interaction. Selenium provides the Alert interface to handle them.
Types of JavaScript Alerts
| Type | Description | User Actions |
|---|---|---|
| Alert | Information display | OK only |
| Confirm | Yes/No question | OK or Cancel |
| Prompt | Text input | Enter text + OK/Cancel |
Handling Simple Alerts
import org.openqa.selenium.Alert;import org.openqa.selenium.support.ui.WebDriverWait;import org.openqa.selenium.support.ui.ExpectedConditions;
// Trigger the alertdriver.findElement(By.id("show-alert")).click();
// Wait for alert and switch to itWebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));Alert alert = wait.until(ExpectedConditions.alertIsPresent());
// Get alert textString alertText = alert.getText();System.out.println("Alert says: " + alertText);
// Accept the alert (click OK)alert.accept();
// Or dismiss the alert (click Cancel)// alert.dismiss();from selenium.webdriver.common.alert import Alertfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EC
# Trigger the alertdriver.find_element(By.ID, "show-alert").click()
# Wait for alert and switch to itwait = WebDriverWait(driver, 10)alert = wait.until(EC.alert_is_present())
# Get alert textalert_text = alert.textprint(f"Alert says: {alert_text}")
# Accept the alert (click OK)alert.accept()
# Or dismiss the alert (click Cancel)# alert.dismiss()const { until } = require('selenium-webdriver');
// Trigger the alertawait driver.findElement(By.id('show-alert')).click();
// Wait for alert and switch to itawait driver.wait(until.alertIsPresent(), 10000);const alert = await driver.switchTo().alert();
// Get alert textconst alertText = await alert.getText();console.log(`Alert says: ${alertText}`);
// Accept the alert (click OK)await alert.accept();
// Or dismiss the alert (click Cancel)// await alert.dismiss();using OpenQA.Selenium;using OpenQA.Selenium.Support.UI;
// Trigger the alertdriver.FindElement(By.Id("show-alert")).Click();
// Wait for alert and switch to itWebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));IAlert alert = wait.Until(ExpectedConditions.AlertIsPresent());
// Get alert textstring alertText = alert.Text;Console.WriteLine($"Alert says: {alertText}");
// Accept the alert (click OK)alert.Accept();
// Or dismiss the alert (click Cancel)// alert.Dismiss();Handling Confirm Dialogs
// Click delete button which shows confirm dialogdriver.findElement(By.id("delete-item")).click();
// Wait for confirm dialogWebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));Alert confirm = wait.until(ExpectedConditions.alertIsPresent());
// Read the confirmation messageString message = confirm.getText();System.out.println("Confirm asks: " + message); // "Are you sure?"
// To proceed with deletion (click OK)confirm.accept();
// Or to cancel (click Cancel)// confirm.dismiss();
// Verify action was taken based on choiceif (driver.findElements(By.id("deleted-item")).isEmpty()) { System.out.println("Item was deleted");}# Click delete button which shows confirm dialogdriver.find_element(By.ID, "delete-item").click()
# Wait for confirm dialogwait = WebDriverWait(driver, 10)confirm = wait.until(EC.alert_is_present())
# Read the confirmation messagemessage = confirm.textprint(f"Confirm asks: {message}") # "Are you sure?"
# To proceed with deletion (click OK)confirm.accept()
# Or to cancel (click Cancel)# confirm.dismiss()
# Verify action was taken based on choiceif not driver.find_elements(By.ID, "deleted-item"): print("Item was deleted")// Click delete button which shows confirm dialogawait driver.findElement(By.id('delete-item')).click();
// Wait for confirm dialogawait driver.wait(until.alertIsPresent(), 10000);const confirm = await driver.switchTo().alert();
// Read the confirmation messageconst message = await confirm.getText();console.log(`Confirm asks: ${message}`); // "Are you sure?"
// To proceed with deletion (click OK)await confirm.accept();
// Or to cancel (click Cancel)// await confirm.dismiss();
// Verify action was taken based on choiceconst deletedElements = await driver.findElements(By.id('deleted-item'));if (deletedElements.length === 0) { console.log('Item was deleted');}// Click delete button which shows confirm dialogdriver.FindElement(By.Id("delete-item")).Click();
// Wait for confirm dialogWebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));IAlert confirm = wait.Until(ExpectedConditions.AlertIsPresent());
// Read the confirmation messagestring message = confirm.Text;Console.WriteLine($"Confirm asks: {message}"); // "Are you sure?"
// To proceed with deletion (click OK)confirm.Accept();
// Or to cancel (click Cancel)// confirm.Dismiss();
// Verify action was taken based on choiceif (driver.FindElements(By.Id("deleted-item")).Count == 0){ Console.WriteLine("Item was deleted");}Handling Prompt Dialogs
// Click button that shows promptdriver.findElement(By.id("show-prompt")).click();
// Wait for promptWebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));Alert prompt = wait.until(ExpectedConditions.alertIsPresent());
// Read the prompt messageSystem.out.println("Prompt asks: " + prompt.getText());
// Enter text into the promptprompt.sendKeys("My custom input");
// Submit the prompt (click OK)prompt.accept();
// Verify the input was receivedWebElement result = driver.findElement(By.id("prompt-result"));System.out.println("You entered: " + result.getText());# Click button that shows promptdriver.find_element(By.ID, "show-prompt").click()
# Wait for promptwait = WebDriverWait(driver, 10)prompt = wait.until(EC.alert_is_present())
# Read the prompt messageprint(f"Prompt asks: {prompt.text}")
# Enter text into the promptprompt.send_keys("My custom input")
# Submit the prompt (click OK)prompt.accept()
# Verify the input was receivedresult = driver.find_element(By.ID, "prompt-result")print(f"You entered: {result.text}")// Click button that shows promptawait driver.findElement(By.id('show-prompt')).click();
// Wait for promptawait driver.wait(until.alertIsPresent(), 10000);const prompt = await driver.switchTo().alert();
// Read the prompt messageconsole.log(`Prompt asks: ${await prompt.getText()}`);
// Enter text into the promptawait prompt.sendKeys('My custom input');
// Submit the prompt (click OK)await prompt.accept();
// Verify the input was receivedconst result = await driver.findElement(By.id('prompt-result'));console.log(`You entered: ${await result.getText()}`);// Click button that shows promptdriver.FindElement(By.Id("show-prompt")).Click();
// Wait for promptWebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));IAlert prompt = wait.Until(ExpectedConditions.AlertIsPresent());
// Read the prompt messageConsole.WriteLine($"Prompt asks: {prompt.Text}");
// Enter text into the promptprompt.SendKeys("My custom input");
// Submit the prompt (click OK)prompt.Accept();
// Verify the input was receivedIWebElement result = driver.FindElement(By.Id("prompt-result"));Console.WriteLine($"You entered: {result.Text}");Unexpected Alerts
Sometimes alerts appear unexpectedly. Handle them defensively:
public boolean isAlertPresent() { try { driver.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; }}
public void dismissIfAlertPresent() { try { Alert alert = driver.switchTo().alert(); System.out.println("Unexpected alert: " + alert.getText()); alert.dismiss(); } catch (NoAlertPresentException e) { // No alert, continue normally }}
public void acceptAllAlerts() { while (isAlertPresent()) { driver.switchTo().alert().accept(); }}
// Use in test setup/teardown@AfterMethodpublic void cleanupAlerts() { dismissIfAlertPresent();}from selenium.common.exceptions import NoAlertPresentException
def is_alert_present(driver): try: driver.switch_to.alert return True except NoAlertPresentException: return False
def dismiss_if_alert_present(driver): try: alert = driver.switch_to.alert print(f"Unexpected alert: {alert.text}") alert.dismiss() except NoAlertPresentException: # No alert, continue normally pass
def accept_all_alerts(driver): while is_alert_present(driver): driver.switch_to.alert.accept()
# Use in test teardowndef teardown_method(self): dismiss_if_alert_present(self.driver)async function isAlertPresent(driver) { try { await driver.switchTo().alert(); return true; } catch (e) { return false; }}
async function dismissIfAlertPresent(driver) { try { const alert = await driver.switchTo().alert(); console.log(`Unexpected alert: ${await alert.getText()}`); await alert.dismiss(); } catch (e) { // No alert, continue normally }}
async function acceptAllAlerts(driver) { while (await isAlertPresent(driver)) { const alert = await driver.switchTo().alert(); await alert.accept(); }}public bool IsAlertPresent(){ try { driver.SwitchTo().Alert(); return true; } catch (NoAlertPresentException) { return false; }}
public void DismissIfAlertPresent(){ try { IAlert alert = driver.SwitchTo().Alert(); Console.WriteLine($"Unexpected alert: {alert.Text}"); alert.Dismiss(); } catch (NoAlertPresentException) { // No alert, continue normally }}
[TearDown]public void CleanupAlerts(){ DismissIfAlertPresent();}HTTP Basic Authentication
For HTTP basic auth popups (not JavaScript alerts):
// Method 1: Include credentials in URLString username = "user";String password = "pass";String url = "https://" + username + ":" + password + "@example.com/protected";driver.get(url);
// Method 2: Using DevTools (Selenium 4 + Chrome)// For more complex authentication scenariosPredicate<URI> uriPredicate = uri -> uri.getHost().contains("example.com");((HasAuthentication) driver).register( uriPredicate, UsernameAndPassword.of(username, password));driver.get("https://example.com/protected");# Method 1: Include credentials in URLusername = "user"password = "pass"url = f"https://{username}:{password}@example.com/protected"driver.get(url)
# Method 2: Using DevTools (Selenium 4 + Chrome)# Available in Selenium 4 with Chrome DevTools Protocol// Method 1: Include credentials in URLconst username = 'user';const password = 'pass';const url = `https://${username}:${password}@example.com/protected`;await driver.get(url);// Method 1: Include credentials in URLstring username = "user";string password = "pass";string url = $"https://{username}:{password}@example.com/protected";driver.Navigate().GoToUrl(url);Modal Dialogs (Not Native Alerts)
Many modern web apps use custom modal dialogs (HTML/CSS) instead of native alerts:
// Custom modals are regular HTML elements, not native alerts
// Wait for modal to be visibleWebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));WebElement modal = wait.until(ExpectedConditions.visibilityOfElementLocated( By.className("modal-dialog")));
// Read modal contentString modalTitle = modal.findElement(By.className("modal-title")).getText();String modalBody = modal.findElement(By.className("modal-body")).getText();
// Interact with modal buttonsWebElement confirmButton = modal.findElement(By.cssSelector(".modal-footer .btn-primary"));confirmButton.click();
// Wait for modal to closewait.until(ExpectedConditions.invisibilityOfElementLocated(By.className("modal-dialog")));# Custom modals are regular HTML elements, not native alerts
# Wait for modal to be visiblewait = WebDriverWait(driver, 10)modal = wait.until(EC.visibility_of_element_located( (By.CLASS_NAME, "modal-dialog")))
# Read modal contentmodal_title = modal.find_element(By.CLASS_NAME, "modal-title").textmodal_body = modal.find_element(By.CLASS_NAME, "modal-body").text
# Interact with modal buttonsconfirm_button = modal.find_element(By.CSS_SELECTOR, ".modal-footer .btn-primary")confirm_button.click()
# Wait for modal to closewait.until(EC.invisibility_of_element_located((By.CLASS_NAME, "modal-dialog")))// Custom modals are regular HTML elements, not native alerts
// Wait for modal to be visibleconst modal = await driver.wait( until.elementLocated(By.className('modal-dialog')), 10000);await driver.wait(until.elementIsVisible(modal), 10000);
// Read modal contentconst modalTitle = await modal.findElement(By.className('modal-title')).getText();const modalBody = await modal.findElement(By.className('modal-body')).getText();
// Interact with modal buttonsconst confirmButton = await modal.findElement(By.css('.modal-footer .btn-primary'));await confirmButton.click();
// Wait for modal to closeawait driver.wait(until.elementIsNotVisible(modal), 10000);// Custom modals are regular HTML elements, not native alerts
// Wait for modal to be visibleWebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));IWebElement modal = wait.Until(ExpectedConditions.ElementIsVisible( By.ClassName("modal-dialog")));
// Read modal contentstring modalTitle = modal.FindElement(By.ClassName("modal-title")).Text;string modalBody = modal.FindElement(By.ClassName("modal-body")).Text;
// Interact with modal buttonsIWebElement confirmButton = modal.FindElement(By.CssSelector(".modal-footer .btn-primary"));confirmButton.Click();
// Wait for modal to closewait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.ClassName("modal-dialog")));Alert Reference
| Method | Description |
|---|---|
getText() | Get alert message |
accept() | Click OK/Yes button |
dismiss() | Click Cancel/No button |
sendKeys(text) | Enter text (prompts only) |
Best Practices
- Always wait for alerts before trying to handle them
- Use try-catch when alerts might not appear
- Distinguish native vs custom dialogs - they need different handling
- Clean up alerts in test teardown
- Avoid credentials in URLs for security when possible
Next Steps
- Windows and Tabs - Handle new windows
- File Uploads - Upload files through dialogs
- Explicit Waits - Wait for alert conditions
- CSS Selectors - Locate modal dialog elements
- Debugging Tips - Troubleshoot alert handling
Finished this lesson?
Mark it complete to track your progress through the course. Saved in this browser only.
Copy-paste recipes
- Handle an Unexpected Alert Without Failing
Configure the session to dismiss surprise alerts automatically, and accept or dismiss expected ones explicitly with a wait.
Errors you may hit
- UnhandledAlertException
Fix Selenium UnhandledAlertException (UnexpectedAlertPresentException in Python, UnexpectedAlertOpenError in JS): surprise alerts and prompt behaviour.