πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
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();