Handle JavaScript Alert in Selenium

Handle JavaScript Alert in Selenium

Many websites make use of JavaScript alert to draw user’s attention to a specific event. It could be an alert to save the unsaved data if the user hit the back button without saving the form data, an important message, prompt to ask user name, etc. In this tutorial, we will learn how to handle JavaScript alert in selenium.

Selenium provides an Alert interface, which is used to handle JavaScript alert. The basic syntax is:

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

Methods provided by Alert interface:

  • accept(); //To select Accept/OK from the prompt
  • dismiss(); // To select Dismiss/Cancel option from the prompt
  • getText(); // To get the prompt message
  • sendKeys(String value); //To send value in prompt type JavaScript alert

Test Website for this tutorial

Click Here

Types of Javascript Alert in Selenium

Handle javascript alert in selenium
Handle javascript alert in selenium

There are typically 3 types of JavaScript alerts:

1. JavaScript Alert with only accept/OK option.

This is a simple javascript alert with only 1 option which is OK or Accept.

alert.accept();

To display the javascript alert pop up message:

alert.getText();

2. JavaScript Alert with Accept and Dismiss options

In addition to alert.accept(); you can also use accept.dismiss(); method for alert which provides both of these options. It is needless to say that you can perform any one of the options at a time.

alert.dismiss();

3. JavaScript alert with a Text box

sendKeys(); method is used to enter string value in these type of javascript alert prompts.

alert.sendKeys("Applied Selenium");

Case Study

Visit the sample test website. There are three buttons which will invoke the respective javascript alert prompts. Demonstrate the valid Alert interface methods for each type of alert.

Handle javascript alert in selenium
Handle javascript alert in selenium – Sample Website

Solution

Visit HERE to configure your initial setup. Once you have created your project, create a new package alertInterface and add a class AlertInterface to it (with the main method).

Write the code till launching the AUT and maximizing the browser, refer below code:

package alertInterface;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class AlertInterface {

    public static WebDriver driver;

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "/home/dhawal/Downloads/chromedriver/chromedriver");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        // navigate to AUT URL
        driver.get("https://the-internet.herokuapp.com/javascript_alerts");
        

    }
}

alert.accept() and alert.getText()

Create a method acceptAlert() and perform the following actions:

  • Find the xPath for first link.
  • Create an object of class RemoteAlert which implements the Alert interface (remember, we cannot instantiate the object of an interface). driver.switchTo().alert() returns an object of RemoteAlert class.
  • print the prompt message. You may use this in other methods as well.
  • Select the OK option from the prompt.
public static void acceptAlert() {
        driver.findElement(By.xpath("//button[@onclick='jsAlert()']")).click();
        Alert alert = driver.switchTo().alert();
        //print alert prompt message
        System.out.println(alert.getText());
        alert.accept();

    }
NOTE:You can call these methods directly in main class and execute.

alert.dismiss()

Create a method dismissAlert() which will click on the second link and select alert.dismiss() method.

public static void dismissAlert() {
        driver.findElement(By.xpath("//button[@onclick='jsConfirm()']")).click();
        Alert alert = driver.switchTo().alert();
        alert.dismiss(); //alert.accept(); is also a valid option

    }

alert.sendKeys(String value)

Create a method promptAlert() which will click on the third link, enter some string value and choose accept.

public static void promptAlert() {
        driver.findElement(By.xpath("//button[@onclick='jsPrompt()']")).click();
        Alert alert = driver.switchTo().alert();
        alert.sendKeys("Applied Selenium");
        alert.accept();//alert.dismiss(); is also a valid option. It will cancel the user input action. 
    }

Full code is written below. The prompt message is also printed for each javascript alert box.

package alertInterface;

import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class AlertInterface {

    public static WebDriver driver;

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "/home/dhawal/Downloads/chromedriver/chromedriver");
        driver = new ChromeDriver();
        driver.manage().window().maximize();
        // navigate to AUT URL
        driver.get("https://the-internet.herokuapp.com/javascript_alerts");
        acceptAlert();
        dismissAlert();
        promptAlert();

    }

    public static void acceptAlert() {
        driver.findElement(By.xpath("//button[@onclick='jsAlert()']")).click();
        Alert alert = driver.switchTo().alert();
        //print alert prompt message
        System.out.println(alert.getText());
        alert.accept();

    }

    public static void dismissAlert() {
        driver.findElement(By.xpath("//button[@onclick='jsConfirm()']")).click();
        Alert alert = driver.switchTo().alert();
        System.out.println(alert.getText());
        alert.dismiss(); //alert.accept(); is also a valid option

    }

    public static void promptAlert() {
        driver.findElement(By.xpath("//button[@onclick='jsPrompt()']")).click();
        Alert alert = driver.switchTo().alert();
        System.out.println(alert.getText());
        alert.sendKeys("Applied Selenium");
        alert.accept();//alert.dismiss(); is also a valid option. It will cancel the user input action. 
    }

}

Upon execution of the above code, it would traverse each link and perform the actions defined in the respective methods. Also, the Result label should be updated to Applied Selenium. The result on console is:

Handle javascript alert in selenium
Console Output

Author: Dhawal Joshi

A post-graduate in MCA, ISTQB & ITIL certified QA with more than 8 years of experience in QA working with a CMMI Level 5 organization as System Analyst. I started my automation journey with HP UFT(formerly known as QTP) and for the past few years, I am using Selenium for automation. I also have experience in Android Application Development, Java, HTML, and VBScript. When I am not working, I like to spend time with my family, cooking and learning new developments in IT.

1 thought on “Handle JavaScript Alert in Selenium

Leave a Reply

Your email address will not be published. Required fields are marked *