Next-Gen App & Browser
Testing Cloud
Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles
Learn how to handle JavaScript alerts in Selenium effectively, including simple, confirmation, and prompt alerts for robust test automation.
Published on: October 5, 2025
Web applications frequently trigger JavaScript alerts to display messages, request confirmations, or capture input from users.
Handling these alerts in Selenium is essential for ensuring test automation can continue without interruptions, validating user interactions, and verifying application behavior under different scenarios.
What Are Alerts in Selenium?
Alerts are generated by the browser using JavaScript to capture user attention or input. They temporarily halt interaction with the main web page until the user responds. Alerts are commonly used for notifications, confirmations, or prompting users for data, making them a key element to handle in automated testing.
Types of Alerts in Selenium
Selenium supports different types of alerts, each serving specific purposes like notifications, confirmations, or prompting user input during tests.
Can Selenium handle custom browser notifications along with alerts?
Selenium cannot directly interact with OS-level notifications or browser push notifications since they exist outside the DOM.
However, you can configure the browser to auto-dismiss these notifications using browser preferences (like ChromeOptions for Chrome or FirefoxProfile for Firefox).
This allows your Selenium tests to continue uninterrupted while ensuring that automated workflows remain stable.
Alerts in web apps are browser-generated dialogs triggered by JavaScript functions like alert(), confirm(), or prompt(). They block interaction until the user responds, pausing workflow.
They are commonly used to display messages, request confirmations, or capture simple input, making it essential to handle them properly in Selenium automation.
Selenium WebDriver uses the Alert interface to manage alerts. You must switch focus to the alert before accepting, dismissing, or entering text to handle it effectively.
To understand how Selenium WebDriver helps with handling alerts, it’s important to first learn what is Selenium WebDriver.
Alert alert = driver.switchTo().alert();
Selenium will throw an UnhandledAlertException if you attempt to accept or dismiss an alert without switching to it first.
For example, some websites display a confirmation alert such as “Are you sure you want to leave this page?”. If the test doesn’t handle this alert, it may fail intermittently with an UnhandledAlertException, making the test flaky. Handling such alerts ensures smooth and consistent execution.
Handling Simple Alert in Selenium: The accept() method in the Alert interface is used for accepting a simple alert. It performs the same action as clicking the OK button.
driver.switchTo().alert().accept();
Handling Confirmation Alert in Selenium: Use the accept() method to confirm the action or the dismiss() method to cancel it.
driver.switchTo().alert().accept(); // Clicks OK
driver.switchTo().alert().dismiss(); // Clicks Cancel
Handling Prompt Alert in Selenium: Use sendKeys() to enter text into the prompt alert, then accept() to submit or dismiss() to cancel.
driver.switchTo().alert().sendKeys("New Text");
driver.switchTo().alert().accept();
Handling getText() in Selenium: The getText() method in Selenium retrieves the visible text of a web element for verification or validation.
driver.switchTo().alert().getText();
Note: Run Selenium tests at scale across 3000+ browsers and OS combinations. Try LambdaTest Now!
In Selenium, switch focus to the alert to validate interactions. Then perform actions like accept, dismiss, or enter input to ensure smooth test flow.
Let’s use the following test scenario to demonstrate handling alerts in Selenium WebDriver.
Test Scenario:
Prerequisites:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.35.0</version>
</dependency>
Code Implementation:
Let’s create a new Java class and name it “AlertTest”. This test class will be used to implement the test scenario we discussed.
public class AlertTest {
private WebDriver driver;
@BeforeClass
public void setup () {
this.driver = new ChromeDriver ();
}
@Test
public void testAlert () {
this.driver.navigate ()
.to ("https://www.lambdatest.com/selenium-playground/javascript-alert-box-demo");
final WebElement clickMeButton = this.driver.findElement (
By.cssSelector ("div > div:nth-child(3) > p > button"));
clickMeButton.click ();
final Alert alert = this.driver.switchTo ()
.alert ();
final String name = "Faisal K";
alert.sendKeys (name);
alert.accept ();
final String promptText = this.driver.findElement (By.id ("prompt-demo"))
.getText ();
assertEquals (promptText, "You have entered " + "'"+ name +"' !");
}
@AfterClass
public void tearDown () {
this.driver.quit ();
}
}
Code Walkthrough:
TestNG assertions provide a mechanism to compare actual and expected results, determining whether a test case passes or fails. They are widely used to validate results and ensure reliable automated testing in Selenium scripts.
Test Execution:
The following screenshot from the IntelliJ IDE shows that the test was executed successfully:
When testing at scale, managing multiple browsers, operating systems, and environments locally can be time-consuming, resource-intensive, and prone to inconsistencies. Running tests on a single machine limits coverage and slows down the feedback loop, especially for large test suites with complex workflows.
Using cloud testing platforms allows teams to execute Selenium tests in parallel across hundreds or thousands of browser/OS combinations, significantly reducing test execution time, improving reliability, and ensuring consistent results across environments.
This approach is particularly useful for handling JavaScript alerts and other dynamic elements that need validation across multiple configurations.
One such platform is LambdaTest, a GenAI-native test execution platform that allows you to perform manual and automated Selenium testing at scale across 3,000+ browsers and OS combinations.
To get started with LambdaTest, follow these steps:
private ChromeOptions getChromeOptions () {
final var browserOptions = new ChromeOptions ();
browserOptions.setPlatformName ("Windows 11");
browserOptions.setBrowserVersion ("latest");
final HashMap<String, Object> ltOptions = new HashMap<String, Object> ();
ltOptions.put ("project", "LambdaTest Selenium Playground");
ltOptions.put ("build", "JavaScript Alert Demo");
ltOptions.put ("name", "Handling JS Alert in Selenium");
ltOptions.put ("w3c", true);
ltOptions.put ("plugin", "java-testNG");
browserOptions.setCapability ("LT:Options", ltOptions);
return browserOptions;
}
"@hub.lambdatest.com/wd/hub";
Code Implementation:
public class AlertTest {
private static final String GRID_URL = "@hub.lambdatest.com/wd/hub";
private static final String LT_ACCESS_KEY = System.getenv ("LT_ACCESS_KEY");
private static final String LT_USERNAME = System.getenv ("LT_USERNAME");
private RemoteWebDriver driver;
private String status = "failed";
@BeforeClass
public void setup () {
try {
this.driver = new RemoteWebDriver (new URL ("https://" + LT_USERNAME + ":" + LT_ACCESS_KEY + GRID_URL),
getChromeOptions ());
} catch (final MalformedURLException e) {
System.out.println ("Could not start the remote session on LambdaTest cloud grid");
}
this.driver.manage ()
.timeouts ()
.pageLoadTimeout (Duration.ofSeconds (10));
}
//..
}
Code Walkthrough:
Test Execution:
The following is the screenshot test execution for handling alerts in Selenium on the LambdaTest cloud grid:
To get started, refer to the documentation on Selenium With TestNG Tutorial.
Handling alerts in Selenium can sometimes be tricky, as unexpected pop-ups or timing issues may cause tests to fail. Proper troubleshooting ensures your tests interact with alerts reliably, reducing flakiness and improving test stability across different browsers and environments.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(30));
wait.until(ExpectedConditions.alertIsPresent());
Handling alerts in Selenium is a crucial aspect of test automation, ensuring that unexpected pop-ups do not disrupt your test execution. Using methods like accept(), dismiss(), getText(), and sendKeys(), you can interact seamlessly with simple, confirmation, and prompt alerts.
Applying these practices leads to more robust and reliable tests, whether running locally or on cloud platforms such as LambdaTest. Mastering alert handling ensures smoother automation and enhances overall test accuracy.
Did you find this page helpful?
More Related Hubs