Handling alerts

What is Alert?
The alert displays an alert box with a specified message and an OK button. An alert box is often appears to display a warning message.

The alerts are blocking the automation test execution and webdriver will throw an exception. In order to avoid it we have to handle the alert programatically.

Types of Alerts
Java scrip provides mainly following three types of alerts

1) Simple alert
In this alert, popup displays on a webpage with alert text and Ok button.


2) Confirmation Alert
Confirmation popup displays on webpage with confirmation text with OK and Cancel button.



3) Prompt Popup
Prompts will have prompt text, Input text box, OK and Cancel buttons.



How to handle Alert in Selenium webdriver?
Following methods are used to handle alerts
  1. accept() to accept the alert
  2. dismiss() to dismiss the alert
  3. getText() to get the text of the alert
  4. sendKeys() to write some text to the alert
Example Code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class DemoAlerts {

 public static void main(String[] args) {

  System.setProperty("webdriver.gecko.driver", "./MyProject/driver/geckodriver.exe");
  WebDriver driver = new FirefoxDriver();
  driver.get("file:///C:/AlertDemo.html");

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

  // Capturing alert message.
  String alertMessage = driver.switchTo().alert().getText();

  // Displaying alert message
  System.out.println(alertMessage);

  // Accepting alert
  alert.accept();

  // alert.dismiss(); to dismiss the alert

 }
}




<-- Previous || Next -->

1 comment: