Back to All Scenarios
Scenario 34 of 100
Popups & Windows
Beginner
Verifying Text Inside a JavaScript Alert
π¬Scenario Overview
Verifying Text Inside a JavaScript Alert
Key Takeaways & Cheat Sheet
- βSwitch focus directly to the target alert dialog first
- βRetrieve alert modal string content using Alert.getText()
- βPerform standard test assertions on the returned text values
- βAccept or dismiss the alert to restore normal test execution
Short Direct Answer
To verify text inside a native JavaScript alert, confirm prompt, or alert modal, switch the driver's active context using `driver.switchTo().alert()`, store the warning text using `Alert.getText()`, perform your assertions, and accept or dismiss the alert to release the browser lock.
β οΈ Senior Warning (Red Flag)
Never click the alert accept button BEFORE retrieving text. Once alert.accept() is called, the alert is dismissed, and any attempt to retrieve text will throw a NoAlertPresentException.
π‘ STAR Deep Dive Explanation & Pro Tip
Always read alert texts first. OS-level popups freeze the page main execution thread, so failing to dismiss them blocks all subsequent operations.
SeleniumAutomation.java
Selenium 4 + Java// β
Wait for alert modal presence
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
// β
Extract message text
String alertMessage = alert.getText();
assert alertMessage.equals("Are you sure you want to delete this record?");
// β
Close alert modal safely
alert.accept();