0
0
Selenium Javatesting~5 mins

Unexpected alert handling in Selenium Java

Choose your learning style9 modes available
Introduction

Sometimes, pop-up alerts appear suddenly during testing. Handling them properly helps tests run smoothly without errors.

When a website shows a pop-up alert unexpectedly during automated testing.
When a confirmation alert blocks further actions in the test.
When you want to automatically accept or dismiss alerts to continue the test.
When alerts interrupt form submissions or page navigation.
When testing error messages shown as alerts.
Syntax
Selenium Java
Alert alert = driver.switchTo().alert();
alert.accept(); // to click OK
alert.dismiss(); // to click Cancel
String alertText = alert.getText();

Use driver.switchTo().alert() to focus on the alert.

accept() clicks OK, dismiss() clicks Cancel or closes the alert.

Examples
This accepts (clicks OK) on the alert.
Selenium Java
Alert alert = driver.switchTo().alert();
alert.accept();
This dismisses (clicks Cancel) on the alert.
Selenium Java
Alert alert = driver.switchTo().alert();
alert.dismiss();
This reads and prints the alert message.
Selenium Java
Alert alert = driver.switchTo().alert();
String message = alert.getText();
System.out.println(message);
Sample Program

This test opens a page with a button that triggers an alert. It switches to the alert, prints its message, then accepts it to continue.

Selenium Java
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class AlertHandlingTest {
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert");

        // Switch to iframe where the alert button is
        driver.switchTo().frame("iframeResult");

        // Click the button to trigger alert
        driver.findElement(By.tagName("button")).click();

        // Switch to alert
        Alert alert = driver.switchTo().alert();

        // Get alert text
        String alertText = alert.getText();
        System.out.println("Alert says: " + alertText);

        // Accept the alert
        alert.accept();

        // Close browser
        driver.quit();
    }
}
OutputSuccess
Important Notes

Always switch to the alert before interacting with it, or Selenium will throw an error.

If you don't handle unexpected alerts, your test may stop abruptly.

Use try-catch blocks to handle alerts that may or may not appear.

Summary

Unexpected alerts can stop tests if not handled.

Use driver.switchTo().alert() to work with alerts.

Accept or dismiss alerts to continue testing smoothly.