JavaScript alerts are commonly used in web applications, and Selenium provides convenient methods to handle them. With Selenium, we can accept or dismiss alerts, send text to input alerts, and retrieve the alert message. We can also use WebDriverWait to wait for an alert to appear before performing any operations on the alert window.
Below, I am providing example scripts in Java, C#, and JavaScript for handling alerts in Selenium.
Handle Alerts
-
Java
-
C#
-
JavaScript
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
public class AlertHandling {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://example.com");
driver.findElement(By.id("alertButton")).click();
// Wait for alert
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
// Get alert text
System.out.println("Alert text: " + alert.getText());
// To dismiss an alert
//alert.dismiss();
// For prompt alerts: send text
alert.sendKeys("Hello");
// Retrieve text from prompt alert (if needed)
String promptText = alert.getText();
// Accept alert
alert.accept();
driver.quit();
}
}
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using SeleniumExtras.WaitHelpers;
using System;
class AlertHandling
{
static void Main()
{
IWebDriver driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://example.com");
driver.FindElement(By.Id("alertButton")).Click();
// Wait for alert
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.AlertIsPresent());
IAlert alert = driver.SwitchTo().Alert();
// Get alert text
Console.WriteLine("Alert text: " + alert.Text);
// To dismiss an alert
// alert.Dismiss();
// For prompt alerts: send text
alert.SendKeys("Hello");
// Retrieve text from prompt alert (if needed)
string promptText = alert.Text;
// Accept the alert
alert.Accept();
driver.Quit();
}
}
const { Builder, By, until } = require("selenium-webdriver");
(async function alertHandling() {
let driver = await new Builder().forBrowser("chrome").build();
try {
await driver.get("https://example.com");
await driver.findElement(By.id("alertButton")).click();
// Wait for alert
await driver.wait(until.alertIsPresent(), 10000);
let alert = await driver.switchTo().alert();
// Get alert text
let text = await alert.getText();
console.log("Alert text: " + text);
// To dismiss an alert:
// await alert.dismiss();
// To send text to a prompt alert:
await alert.sendKeys("Hello");
// To get text again (e.g., from prompt):
let promptText = await alert.getText();
// Accept alert
await alert.accept();
} finally {
await driver.quit();
}
})();