In this tutorial, we are going to learn about different types of alert found in web application and how to handle Alert in Selenium WebDriver. We will also see how do we accept and dismiss the alert depending upon the alert types.

What is Alert?


Alert is a small dialogs message box which displays an important notification on screen to give certain kind of information to users or ask for permission to perform a certain kind of operation. It may be anything like validation errors, warnings, accepting an input value or related to functionalities. When the webpage displays alert, users have to take actions before processing further.
For example,
Key point: Alert is an interface.

Types of Alert


There are three types of alerts. They are as follows:

1. Simple Alert:

A simple alert will show information or warning on the screen and expect the user to click on an OK button to continue an ongoing process. A simple example of simple alert has been shown in the below screenshot.
Simple alert in selenium webdriver

2. Prompt Alert:

This Prompt Alert will show a message on the screen and expect the user to enter a value using sendkeys("input...") of selenium webdriver in before continuing with an ongoing process. i.e. when a prompt box pops up, user will have to send or enter a text and click on either OK button or Cancel button to proceed.
If user clicks on OK button, the box returns input value. If user clicks on Cancel button, the box returns null. An example of a prompt alert is shown in the below screenshot.
Prompt alert in selenium

3. Confirmation Alert:

This confirmation alert will show a message on the screen and expect the user to accept or dismiss alert before continuing with an ongoing operation. i.e. When a confirm alert box is displayed on the screen, the user will have to click on either OK or Cancel button to proceed further operation.
If user clicks on the OK button, the confirm box will return a true value. If user clicks on the Cancel button, it returns false. An example of confirmation alert can be shown in the below screenshot.
Confirmation alert in selenium

Methods of Alert Interface


Alert interface provides the following methods to handle modal dialogs which are widely used in Selenium Webdriver.

1. void dismiss()

This method is used to clicking on the 'Cancel' button of the alert. It has the following general form.

Syntax:

        driver.switchTo().alert().dismiss();

2. void accept()

This method is used to clicking on the 'Ok' button of the alert. The following general form is given below:

Syntax:

        driver.switchTo().alert().accept();

3. String getText()

This method is used to capture alert message.

Syntax:

       driver.switchTo().alert().getText(); 

4. void sendKeys(String stringToSend)

This method is used to send or input data to the alert box.

Syntax:

       driver.switchTo().alert().sendKeys("Text");

Handling a Simple JavaScript Alert box


Let's take a test case in which we will automate the following scenarios:
1. Invoke Firefox Browser
2. Open URL: https://seleniumtesting08.blogspot.com/2019/07/alert-test.html
3. Click on the "Generate Simple Alert box" button.
4. Close the browser.


We will create our test case step by step so that you can complete understanding of how to handle simple alert in Selenium WebDriver.
Program source code: 1
    package practiceAlert; import java.util.concurrent.TimeUnit; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class SimpleAlertPop { public static void main(String[] args) { // Create an object of FirefoxDriver class. WebDriver driver = new FirefoxDriver(); String URL="https://seleniumtesting08.blogspot.com/2019/07/alert-test.html"; driver.get(URL); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().window().maximize(); // Click on simple alert button to show alert box. WebElement element = driver.findElement(By.xpath("//input[@id='simple']")); element.click(); // Switching to Alert from webpage. Alert alert=driver.switchTo().alert(); // Get or read the text displayed on Alert popup and save it in a string using variable "getText" in order to print it later. String getText=driver.switchTo().alert().getText(); System.out.println(getText); // Check that the correct message is displayed to the user Alert box. if(getText.equalsIgnoreCase("Hello! I am a simple alert box!")) { // Display a message that indicates whether verification was successful. System.out.println("It worked, the expected simple alert was shown"); } else { System.out.println("Something went wrong, expected simple alert was not shown"); } // Click OK button, by calling accept() method. alert.accept(); driver.close(); } }
    Output: Hello! I am a simple alert box! It worked, the expected simple alert was shown.
How it works...
1. Selenium WebDriver provides an Alert interface for handling alert popup. It provides various kind of methods for interacting with alert box. The driver.switchTo().alert() method returns an object of alert for alert box appeared on the screen.
         Alert alert=driver.switchTo().alert();

2. You might need to verify what message is displayed in alert box. You can get or read the text from alert box by calling getText() method provided by Alert interface.
        String getText=driver.switchTo().alert().getText(); or
        String getText=alert.getText();

3. An alert box can be closed by clicking on OK button. It can be done by calling accept() method. This is as follows:
    alert.accept(); or
    driver.switchTo().alert().accept();

4. If you want to create an explicit wait condition for alert to be displayed on the webpage, you can use WebDriverWet class and alertIsPresent() method of the ExpectedConditions class as shown in the following example code.
    new WebDriverWait(driver, 10).until(ExpectedConditions.alertIsPresnt());
// Switching to alert.
    Alert alert=driver.switchTo().alert();
This concept is useful when there is delay after a user performs an action and an alert is displayed.     

NoAlertPresentException

If you try to access an alert box that does not exist, driver.switchTo().alert() method will throw an exception called NoAlertPresentException.

Handling Confirmation Alert box


Let's create one more test case where we will handle confirmation alert box displayed on web page using alert interface of Selenium WebDriver.
Program source code 2:
In this coding, we will create a class ConfirmationAlert where we will accept confirm box and verify a message on the webpage when the confirm box is accepted i.e when OK button is clicked. Let's see the coding.
    package practiceAlert; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class ConfirmAcceptTest { public static void main(String[] args) { WebDriver driver=new FirefoxDriver(); String URL="https://seleniumtesting08.blogspot.com/2019/07/alert-test.html"; driver.get(URL); driver.manage().window().maximize(); WebElement element=driver.findElement(By.xpath("//button[@id='confirm']")); element.click(); // Switching to alert from web page. Alert alert=driver.switchTo().alert(); String getText=driver.switchTo().alert().getText(); System.out.println(getText); if(getText.equalsIgnoreCase("This is a confirm alert. Do you want to accept or cancel?")) { alert.accept(); System.out.println("You accepted alert"); } else { alert.dismiss(); System.out.println("You dismissed alert"); } driver.close(); } }
    Output: This is a confirm alert. Do you want to accept or cancel? You accepted alert

Handling a Prompt box


In the previous sections, we have used three methods of alert interface in the coding.  Now let's make a test that handles prompt box. We will send text using sendKeys(String sendToString) method into the input field of the prompt box and later verify if the same value is displayed on the webpage as shown in the following code example.
Program source code 3:
    package practiceAlert; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class PromptAlertTest { public static void main(String[] args) { WebDriver driver=new FirefoxDriver(); String URL="https://seleniumtesting08.blogspot.com/2019/07/alert-test.html"; driver.get(URL); driver.manage().window().maximize(); // Click on confirm button to show prompt alert box. WebElement element=driver.findElement(By.xpath("//button[@id='prompt']")); element.click(); // Switching to alert from web page. Alert alert=driver.switchTo().alert(); // Enter some text on prompt alert box. alert.sendKeys("Deep"); alert.accept(); // Check webpage displays message with text entered in prompt box. WebElement displayMessage=driver.findElement(By.id("prompt_demo")); String getText=displayMessage.getText(); System.out.println(getText); if(getText.equalsIgnoreCase("Hello Deep! How are you today?")){ System.out.println("Exact matched"); } else { System.out.println("Something went wrong"); } driver.close(); } }
    Output: Hello Deep! How are you today? Exact matched
Final words

Hope that this tutorial has covered almost all important points of Alert in Selenium WebDriver and related example scenarios. I hope that you will have understood concept and enjoyed it.
Thanks for reading!