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.
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();
}
}