Handling Java Alerts using Selenium Webdriver


2 min read

Understanding Java Alerts ๐Ÿค”

Java Alerts are used to convey important information, warnings, or prompt user interaction. They can appear as simple informational messages, confirmations, or input prompts.

Types of Java Alerts:

  1. Alerts: Simple notifications that require acknowledgment.

  2. Confirmations: Alerts with options to confirm or cancel.

  3. Prompts: Alerts that prompt the user to enter input.

Selenium Commands for Java Alerts ๐Ÿ•น

Alert Interface:

Selenium provides the Alert interface to interact with Java Alerts. Here are some essential methods:

  • Switch to Alert:

      Alert alert = driver.switchTo().alert();
  • Accept Alert (OK/Yes):

  • Dismiss Alert (Cancel/No):

  • Get Alert Text:

      String alertText = alert.getText();
  • Enter Text in Prompt:


Handling Different Alert Types ๐Ÿ”„

  1. Simple Alerts: Simple alerts require only acknowledgment. Use accept() to close them.

     Alert simpleAlert = driver.switchTo().alert();
  2. Confirm Alerts: Confirm alerts have options to confirm or cancel. Use accept() for confirmation and dismiss() for cancellation.

     Alert confirmAlert = driver.switchTo().alert();
     confirmAlert.accept(); // Confirm
     // OR
     confirmAlert.dismiss(); // Cancel
  3. Prompt Alerts: Prompt alerts prompt the user to enter input. Use sendKeys() to enter text and accept() to confirm.

     Alert promptAlert = driver.switchTo().alert();

Example: Handling a Login Alert ๐ŸŒ

Consider a scenario where a website prompts an alert upon incorrect login credentials. You can handle it like this:

// Locate login elements and trigger login attempt

// Handle alert
Alert loginAlert = driver.switchTo().alert();
String alertText = loginAlert.getText();
System.out.println("Alert Text: " + alertText);

Conclusion ๐ŸŽ“

Mastering Java Alerts is essential for robust Selenium test automation. With the Alert interface, you can seamlessly handle alerts of different types, ensuring your automated tests handle pop-ups gracefully. Happy testing! ๐Ÿš€๐Ÿšฆ