Skip to main content
SeleniumDecoded

Alerts and Popups

Handle JavaScript alerts, confirms, prompts, and authentication dialogs.

Selenium 3 & 4 Stable

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

TypeDescriptionUser Actions
AlertInformation displayOK only
ConfirmYes/No questionOK or Cancel
PromptText inputEnter text + OK/Cancel

Handling Simple Alerts

Accept or Dismiss Alerts
Selenium 3 & 4 Stable
import org.openqa.selenium.Alert;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
// Trigger the alert
driver.findElement(By.id("show-alert")).click();
// Wait for alert and switch to it
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
// Get alert text
String 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 Alert
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Trigger the alert
driver.find_element(By.ID, "show-alert").click()
# Wait for alert and switch to it
wait = WebDriverWait(driver, 10)
alert = wait.until(EC.alert_is_present())
# Get alert text
alert_text = alert.text
print(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 alert
await driver.findElement(By.id('show-alert')).click();
// Wait for alert and switch to it
await driver.wait(until.alertIsPresent(), 10000);
const alert = await driver.switchTo().alert();
// Get alert text
const 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 alert
driver.FindElement(By.Id("show-alert")).Click();
// Wait for alert and switch to it
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IAlert alert = wait.Until(ExpectedConditions.AlertIsPresent());
// Get alert text
string 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

Confirm Dialog Handling
Selenium 3 & 4 Stable
// Click delete button which shows confirm dialog
driver.findElement(By.id("delete-item")).click();
// Wait for confirm dialog
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert confirm = wait.until(ExpectedConditions.alertIsPresent());
// Read the confirmation message
String 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 choice
if (driver.findElements(By.id("deleted-item")).isEmpty()) {
System.out.println("Item was deleted");
}
# Click delete button which shows confirm dialog
driver.find_element(By.ID, "delete-item").click()
# Wait for confirm dialog
wait = WebDriverWait(driver, 10)
confirm = wait.until(EC.alert_is_present())
# Read the confirmation message
message = confirm.text
print(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 choice
if not driver.find_elements(By.ID, "deleted-item"):
print("Item was deleted")
// Click delete button which shows confirm dialog
await driver.findElement(By.id('delete-item')).click();
// Wait for confirm dialog
await driver.wait(until.alertIsPresent(), 10000);
const confirm = await driver.switchTo().alert();
// Read the confirmation message
const 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 choice
const deletedElements = await driver.findElements(By.id('deleted-item'));
if (deletedElements.length === 0) {
console.log('Item was deleted');
}
// Click delete button which shows confirm dialog
driver.FindElement(By.Id("delete-item")).Click();
// Wait for confirm dialog
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IAlert confirm = wait.Until(ExpectedConditions.AlertIsPresent());
// Read the confirmation message
string 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 choice
if (driver.FindElements(By.Id("deleted-item")).Count == 0)
{
Console.WriteLine("Item was deleted");
}

Handling Prompt Dialogs

Prompt Dialog with Input
Selenium 3 & 4 Stable
// Click button that shows prompt
driver.findElement(By.id("show-prompt")).click();
// Wait for prompt
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
Alert prompt = wait.until(ExpectedConditions.alertIsPresent());
// Read the prompt message
System.out.println("Prompt asks: " + prompt.getText());
// Enter text into the prompt
prompt.sendKeys("My custom input");
// Submit the prompt (click OK)
prompt.accept();
// Verify the input was received
WebElement result = driver.findElement(By.id("prompt-result"));
System.out.println("You entered: " + result.getText());
# Click button that shows prompt
driver.find_element(By.ID, "show-prompt").click()
# Wait for prompt
wait = WebDriverWait(driver, 10)
prompt = wait.until(EC.alert_is_present())
# Read the prompt message
print(f"Prompt asks: {prompt.text}")
# Enter text into the prompt
prompt.send_keys("My custom input")
# Submit the prompt (click OK)
prompt.accept()
# Verify the input was received
result = driver.find_element(By.ID, "prompt-result")
print(f"You entered: {result.text}")
// Click button that shows prompt
await driver.findElement(By.id('show-prompt')).click();
// Wait for prompt
await driver.wait(until.alertIsPresent(), 10000);
const prompt = await driver.switchTo().alert();
// Read the prompt message
console.log(`Prompt asks: ${await prompt.getText()}`);
// Enter text into the prompt
await prompt.sendKeys('My custom input');
// Submit the prompt (click OK)
await prompt.accept();
// Verify the input was received
const result = await driver.findElement(By.id('prompt-result'));
console.log(`You entered: ${await result.getText()}`);
// Click button that shows prompt
driver.FindElement(By.Id("show-prompt")).Click();
// Wait for prompt
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IAlert prompt = wait.Until(ExpectedConditions.AlertIsPresent());
// Read the prompt message
Console.WriteLine($"Prompt asks: {prompt.Text}");
// Enter text into the prompt
prompt.SendKeys("My custom input");
// Submit the prompt (click OK)
prompt.Accept();
// Verify the input was received
IWebElement result = driver.FindElement(By.Id("prompt-result"));
Console.WriteLine($"You entered: {result.Text}");

Unexpected Alerts

Sometimes alerts appear unexpectedly. Handle them defensively:

Handling Unexpected Alerts
Selenium 3 & 4 Stable
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
@AfterMethod
public 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 teardown
def 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):

HTTP Basic Authentication
Selenium 3 & 4 Medium
// Method 1: Include credentials in URL
String 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 scenarios
Predicate<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 URL
username = "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 URL
const username = 'user';
const password = 'pass';
const url = `https://${username}:${password}@example.com/protected`;
await driver.get(url);
// Method 1: Include credentials in URL
string username = "user";
string password = "pass";
string url = $"https://{username}:{password}@example.com/protected";
driver.Navigate().GoToUrl(url);

Many modern web apps use custom modal dialogs (HTML/CSS) instead of native alerts:

Handling Custom Modal Dialogs
Selenium 3 & 4 Stable
// Custom modals are regular HTML elements, not native alerts
// Wait for modal to be visible
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement modal = wait.until(ExpectedConditions.visibilityOfElementLocated(
By.className("modal-dialog")
));
// Read modal content
String modalTitle = modal.findElement(By.className("modal-title")).getText();
String modalBody = modal.findElement(By.className("modal-body")).getText();
// Interact with modal buttons
WebElement confirmButton = modal.findElement(By.cssSelector(".modal-footer .btn-primary"));
confirmButton.click();
// Wait for modal to close
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.className("modal-dialog")));
# Custom modals are regular HTML elements, not native alerts
# Wait for modal to be visible
wait = WebDriverWait(driver, 10)
modal = wait.until(EC.visibility_of_element_located(
(By.CLASS_NAME, "modal-dialog")
))
# Read modal content
modal_title = modal.find_element(By.CLASS_NAME, "modal-title").text
modal_body = modal.find_element(By.CLASS_NAME, "modal-body").text
# Interact with modal buttons
confirm_button = modal.find_element(By.CSS_SELECTOR, ".modal-footer .btn-primary")
confirm_button.click()
# Wait for modal to close
wait.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 visible
const modal = await driver.wait(
until.elementLocated(By.className('modal-dialog')),
10000
);
await driver.wait(until.elementIsVisible(modal), 10000);
// Read modal content
const modalTitle = await modal.findElement(By.className('modal-title')).getText();
const modalBody = await modal.findElement(By.className('modal-body')).getText();
// Interact with modal buttons
const confirmButton = await modal.findElement(By.css('.modal-footer .btn-primary'));
await confirmButton.click();
// Wait for modal to close
await driver.wait(until.elementIsNotVisible(modal), 10000);
// Custom modals are regular HTML elements, not native alerts
// Wait for modal to be visible
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement modal = wait.Until(ExpectedConditions.ElementIsVisible(
By.ClassName("modal-dialog")
));
// Read modal content
string modalTitle = modal.FindElement(By.ClassName("modal-title")).Text;
string modalBody = modal.FindElement(By.ClassName("modal-body")).Text;
// Interact with modal buttons
IWebElement confirmButton = modal.FindElement(By.CssSelector(".modal-footer .btn-primary"));
confirmButton.Click();
// Wait for modal to close
wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.ClassName("modal-dialog")));

Alert Reference

MethodDescription
getText()Get alert message
accept()Click OK/Yes button
dismiss()Click Cancel/No button
sendKeys(text)Enter text (prompts only)

Best Practices

  1. Always wait for alerts before trying to handle them
  2. Use try-catch when alerts might not appear
  3. Distinguish native vs custom dialogs - they need different handling
  4. Clean up alerts in test teardown
  5. Avoid credentials in URLs for security when possible

Next Steps