0
0
Selenium Javatesting~5 mins

Alert accept and dismiss in Selenium Java

Choose your learning style9 modes available
Introduction

Alerts are pop-up messages in web pages. Accepting or dismissing them helps control the test flow.

When a web page shows a confirmation pop-up and you want to click OK.
When a warning alert appears and you want to cancel or close it.
When testing form submissions that trigger alert messages.
When automating user actions that involve alert pop-ups.
When verifying alert text before accepting or dismissing.
Syntax
Selenium Java
Alert alert = driver.switchTo().alert();
alert.accept(); // to click OK
alert.dismiss(); // to click Cancel or close

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

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

Examples
This accepts the alert pop-up by clicking OK.
Selenium Java
Alert alert = driver.switchTo().alert();
alert.accept();
This dismisses the alert pop-up by clicking Cancel or closing it.
Selenium Java
Alert alert = driver.switchTo().alert();
alert.dismiss();
This reads the alert message, prints it, then accepts the alert.
Selenium Java
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
System.out.println(alertText);
alert.accept();
Sample Program

This test opens a page with JavaScript alerts, clicks a button to show an alert, reads and prints the alert text, accepts the alert, then prints the result message on the page.

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 AlertTest {
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
        driver.get("https://the-internet.herokuapp.com/javascript_alerts");

        // Click button to trigger alert
        driver.findElement(By.xpath("//button[text()='Click for JS Alert']")).click();

        // Switch to alert and accept it
        Alert alert = driver.switchTo().alert();
        String alertMessage = alert.getText();
        System.out.println("Alert says: " + alertMessage);
        alert.accept();

        // Verify result text
        String result = driver.findElement(By.id("result")).getText();
        System.out.println("Result text: " + result);

        driver.quit();
    }
}
OutputSuccess
Important Notes

Always switch to the alert before interacting with it.

Accepting confirms the alert; dismissing cancels or closes it.

Alerts block the page until handled, so tests wait for alert actions.

Summary

Use driver.switchTo().alert() to access alerts.

accept() clicks OK, dismiss() clicks Cancel.

Handle alerts to keep tests running smoothly.