How to handle Alert in Selenium WebDriver

In this tutorial, we are going to learn about different types of alert found in web applications 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 that displays an important notification on the screen to give users a certain kind of information 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 action before processing further.

Key point: Alert is an interface.

Types of Alert in Selenium


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

  • Simple alert
  • Prompt alert
  • Confirmation alert

Let’s discuss them one by one in brief.

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 a simple alert has been shown in the below screenshot.

Simple alert in Selenium

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 before continuing with an ongoing process.

That is, when a prompt box pops up, user will have to send or enter a text and click on either the OK button or Cancel button to proceed.


If a user clicks on the OK button, the box returns input value. If a 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 the alert before continuing with an ongoing operation.

That is, when a confirm alert box is displayed on the screen, the user will have to click on either the OK or Cancel button to proceed with the 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 a confirmation alert can be shown in the below screenshot.

Confirmation alert in Selenium

Methods of Alert Interface in Selenium


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. The general syntax to call dismiss() method is as follows:

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

2. void accept(): This method is used to clicking on the ‘Ok’ button of the alert. The general syntax to call accept() method is given below:

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

3. String getText(): This method is used to capture the alert message. The general syntax to call getText() method is as follows:

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

4. void sendKeys(String stringToSend): This method is used to send or input data to the alert box. The general syntax to call sendKeys() method is as follows:

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

Handling Simple JavaScript Alert box


Let’s create a test case in which we will automate the following scenario:

1. Invoke Firefox Browser
2. Open URL: https://selenium08.blogspot.com/2019/07/alert-test.html
3. Click on the “Generate Simple Alert box” button.
4. Close the browser.

Look at step by step in the following source code to complete understanding 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://selenium08.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 popups. It provides various kinds of methods for interacting with the alert boxes.

The driver.switchTo().alert() method returns an object of alert for alert box appeared on the screen.

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

2. We might need to verify what message is displayed in alert box. We can get or read the text from the 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.

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

How to handle Confirmation Alert box in Selenium


Let’s create one more test case where we will handle confirmation alert box displayed on the web page using alert interface of Selenium WebDriver.
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.

Program source code 2:

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://selenium08.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

How to handle Prompt Alert box in Selenium


In the previous sections, we have used three methods of alert interface in the coding.  Now let’s make a test that handles the 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://selenium08.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

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 the concepts and enjoyed them.
Thanks for reading!!!
Next ⇒ Actions class in Selenium

⇐ PrevNext ⇒

Leave a Comment