Selenium + Java · Lesson 20 of 44
Module 20: Alerts & Popups
Your task
Implement acceptAlertAndGetText:
Write it in the editor, then press Check answer (Ctrl + Enter).
import org.openqa.selenium.Alert;
// Simple Alert (OK only):
Alert simpleAlert = driver.switchTo().alert();
System.out.println("Alert text: " + simpleAlert.getText());
simpleAlert.accept();
// Confirm Dialog (OK / Cancel):
Alert confirmDialog = driver.switchTo().alert();
confirmDialog.dismiss(); // Clicks Cancel
// Prompt Dialog (Input + OK / Cancel):
Alert prompt = driver.switchTo().alert();
prompt.sendKeys("QA Confirmation");
prompt.accept();Browser JavaScript dialogs block DOM execution until the user accepts or dismisses them. In this lesson, you will master the Alert interface: accept, dismiss, getText, and sendKeys for prompt dialogs. Let's handle alerts!
Part of the Selenium + Java course (Selenium with Java). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.
It throws NoAlertPresentException. Always use WebDriverWait with ExpectedConditions.alertIsPresent() before switching.
Ready? Solve the task in the editor
Use Check answer to mark it complete. Hints are there if you need them.
___