Turn your manual testers into automation experts! Request a DemoStart testRigor Free

Navigating UnexpectedAlertPresentException in Selenium

When you perform WebDriver operations, if an alert, confirmation, or prompt box appears unexpectedly, the script is not prepared to handle that. Then, the script moves on to the next execution step, and UnexpectedAlertPresentException is thrown in Selenium. You need to handle these pop-up alerts as they can block further execution.

Read this article to learn more about alerts and handling NoAlertPresentException in Selenium.

Why UnexpectedAlertPresentException Happens?

Below are a few reasons why you might encounter UnexpectedAlertPresentException in Selenium:

Unhandled Alerts in Script

This is the most common reason for the exception. When an alert/confirmation/prompt box appears on the screen, and the WebDriver does not handle it, i.e., accept, dismiss, or read its content. The test script then tries to execute the following command, and UnexpectedAlertPresentException is thrown.

Example: The script clicks a button, and an alert is triggered. Without handling the alert, the script interacts with another button. This scenario will cause UnexpectedAlertPresentException.
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.id("triggerAlertButton")).click(); // This triggers an alert

// Attempt to click another button without handling the alert
driver.findElement(By.id("otherButton")).click(); // This will throw UnexpectedAlertPresentException

Asynchronous Operations Trigerring Alerts

Asynchronous operations such as AJAX calls may trigger JavaScript alerts unexpectedly. If the delay is not managed in the script for such alerts, then the exception is thrown by Selenium.

Example: When an AJAX call completion triggers an alert, but the script has already moved on to the next step without waiting for the AJAX call to finish as below:
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.id("triggerAjaxCall")).click(); // This triggers an AJAX call that will eventually show an alert

// Assuming the AJAX call will complete in 5 seconds
Thread.sleep(5000); // Poor way to handle timing, just for demonstration

// Trying to interact with the page without checking for alert
driver.findElement(By.id("afterAjax")).click(); // Might throw UnexpectedAlertPresentException if the alert is present

Browser-specific Alerts/Behavior

Different browsers may handle alerts differently. A few scripts may work fine in one browser but may encounter unexpected alerts in another. These alerts might be unhandled by the script and cause UnexpectedAlertPresentException.

Example: A test script executes smoothly in Chrome but faces unexpected alerts in Firefox, and then UnexpectedAlertPresentException occurs.

Alert Timing Issues

Alerts that appear on page load or due to some background operations might not be appropriately synchronized with the WebDriver’s commands. This may lead to unexpected alerts and then UnexpectedAlertPresentException eventually.

Example: An alert appears during a page load, but the script starts interacting with the page elements before handling the alert.

How to Fix UnexpectedAlertPresentException?

Here are a few resolutions that might help you to fix UnexpectedAlertPresentException in Selenium.

Handle Alerts Explicitly

Whenever an action is performed in the scripts, handle the triggered alerts explicitly by accepting, dismissing, etc., as shown below:
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");
driver.findElement(By.id("triggerAlertButton")).click(); // This triggers an alert

try {
  Alert alert = driver.switchTo().alert();
  alert.accept(); // or alert.dismiss(); to cancel the alert
} catch (NoAlertPresentException e) {
  System.out.println("No alert was present");
}

// Continue with other actions

Wait for Alerts in Asynchronous Operations

If there are asynchronous operations present in your script, then alerts might appear as a result. Use explicit waits to wait for the alert as below:
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
driver.get("http://example.com");

driver.findElement(By.id("triggerAjaxCall")).click(); // This triggers an AJAX call that may eventually show an alert

try {
  wait.until(ExpectedConditions.alertIsPresent());
  Alert alert = driver.switchTo().alert();
  alert.accept(); // Handle the alert
} catch (TimeoutException e) {
  System.out.println("Alert did not appear within the specified time");
}

// Continue with other actions

Handle Alerts After Page Load

If you know that alerts could appear immediately after or during page load, then you need to handle them in the script before starting any other actions.
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");

try {
  Alert alert = driver.switchTo().alert();
  alert.accept(); // Handling alert on page load
} catch (NoAlertPresentException e) {
  System.out.println("No alert on page load");
}

// Now safe to proceed with other actions

Use Try-Catch Blocks

In the Java-Selenium framework, use try-catch blocks to gracefully handle scenarios where you think an unexpected alert might get triggered. This helps you code further actions or log the occurrence of unforeseen alerts.
WebDriver driver = new ChromeDriver();
driver.get("http://example.com");

try {
  driver.findElement(By.id("someElement")).click();
  
  // More actions...

} catch (UnexpectedAlertPresentException e) {
  Alert alert = driver.switchTo().alert();
  System.out.println("Unexpected alert handled: " + alert.getText());
  alert.accept();
  
  // Optionally, retry the action or perform alternative steps

}

Cross-browser Testing

Test your scripts across different browsers to handle browser-specific alert behaviors and rectify any errors and exceptions accordingly for smooth execution. Read more about cross-browser testing.

Bypass UnexpectedAlertPresentException with testRigor

You may have understood the reasons and resolutions to UnexpectedAlertPresentException in Selenium. However, it is easier said than done, and if you want to bypass all these exceptions and just focus on software testing, then we have a powerful solution for you.

testRigor is a generative AI-based automation testing tool that is codeless and requires no programming knowledge to write test cases. Anyone in your team can write and execute test cases in plain English as below:
login
click "Men Clothing"
scroll down
click "Men's cargo shorts"
click "brown"
click "Size 34"
click "Add to cart"
check that page contains "Your order is nearly complete!"
accept prompt with value "Order Successful!"

This is the simplicity of test cases in testRigor, where you can use the UI text that you see on the screen as identifiers for elements. No more unstable CSS/XPath locators to put you in trouble with maintenance and frequent script updates. With testRigor, you need not add explicit waits to wait for the page elements to load completely; testrigor is intelligent enough to handle these scenarios automatically.

Perform web, mobile, desktop, API, cross-browser, and cross-platform testing singlehandedly with testRigor in plain English. It has supportive integrations with all significant test management, defect management, infrastructure provider, ERP, and CRM tools. It’s time to bid goodbye to the irritating Selenium exceptions forever!

Conclusion

Selenium has been everyone’s test automation partner for a long. But the current Agile and DevOps faster release cycles demand more. It is not worth spending hours handling Selenium errors and exceptions when that effort and time could bring out something more productive and valuable.

If there are intelligent alternatives available, why not use them for the benefit of every stakeholder involved? Put minimum effort into script maintenance with testRigor, which has in-built self-healing capabilities. Build robust tests faster with ease and attain more test coverage to release a high-quality product within budget.

You're 15 Minutes Away From Automated Test Maintenance and Fewer Bugs in Production
Simply fill out your information and create your first test suite in seconds, with AI to help you do it easily and quickly.
Achieve More Than 90% Test Automation
Step by Step Walkthroughs and Help
14 Day Free Trial, Cancel Anytime
“We spent so much time on maintenance when using Selenium, and we spend nearly zero time with maintenance using testRigor.”
Keith Powe VP Of Engineering - IDT
Related Articles

SAP Concur Testing

Concur Technologies, now SAP Concur, is an American software-as-a-service (SaaS) company providing travel and expense management ...

Authorize.net Testing

You need a payment gateway in several scenarios, especially when you are running a business that requires secure, efficient, and ...

KYC Portal CLM Testing

KYC Portal CLM is an award-winning Client Lifecycle Management (CLM) platform designed to streamline and automate the Know Your ...
On our website, we utilize cookies to ensure that your browsing experience is tailored to your preferences and needs. By clicking "Accept," you agree to the use of all cookies. Learn more.
Cookie settings
Privacy Overview
This site utilizes cookies to enhance your browsing experience. Among these, essential cookies are stored on your browser as they are necessary for ...
Read more
Strictly Necessary CookiesAlways Enabled
Essential cookies are crucial for the proper functioning and security of the website.
Non-NecessaryEnabled
Cookies that are not essential for the website's functionality but are employed to gather additional data. You can choose to opt out by using this toggle switch. These cookies gather data for analytics and performance tracking purposes.