Open In App

How to Handle Alert in Selenium using Java?

Last Updated : 25 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Imagine filling out a form online and accidentally missing some information. You only know if you made a mistake if the website tells you somehow, like with a pop-up message. This article explains what those pop-up messages are called in Selenium (alerts) and how to deal with them in your automated tests.

Prerequisites

  1. Eclipse IDE: Before downloading also make sure that your device has Java JDK. If you don’t have, to install Java refer to this: How to Download and Install Java for 64-bit machine?
  2. Install Eclipse IDE by referring to this article Eclipse IDE for Java Developers.
  3. Selenium: Download the Selenium latest stable version here.
  4. Web Driver: Download the Microsoft Edge Webdriver according to your version here.

Note: 

To Open a Chrome Browser Using Selenium please refer to this article How to Open a Chrome Browser Using Selenium in Java? 

What are Alerts in Selenium?

An Alert is nothing but a small message box that appears on the screen to give some kind of information and give a warning for a potentially damaging operation or permission to perform that operation.

Types of Alerts in Selenium

There are three types of Alert in Selenium, described as follows:

  1. Simple Alert
  2. Prompt Alert
  3. Confirmation Alert

An Alert is nothing but a small message box that appears on the screen to give some kind of information and give a warning for a potentially damaging operation or permission to perform that operation.

1. Simple Alert

The simple alert in selenium shows some information or warning on the window.

Simple Alert

 

2. Confirmation Alert

The confirmation alert asks for the permission to do some type of operations.

Confirmation alert

3. Prompt Alert

Prompt Alert asks some input from the user.

Prompt Alert

How to Handle Alerts in Selenium?

There are the four methods that we would be using along with the Alert interface.

1. void dismiss()

The void dismiss method is used to click on the ‘Cancel’ button of the alert.

Java




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


2. void accept() 

The void accept method is used to click on the ‘OK’ button of the alert.

Java




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


3. String getText() 

The void accept method is used to capture the alert message..

Java




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


4. void sendKeys(String stringToSend)

It is used to send some data to the prompt alert.

Java




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


Example of Alert Handling Using Selenium

  1. Launch the web browser and open the webpage “https://demoqa.com/alerts
  2. Click on the confirmation alert button
  3. Accept the alert
  4. Click on the confirmation alert button again
  5. Reject the alert

Selenium test Script to Handle Alerts:

Java




package GFG_Maven.GFG_MAven;
 
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class Geeks {
    public static void main(String args[]) throws InterruptedException {
       
        System.setProperty("webdriver.chrome.driver","C:\\Users\\ADMIN\\Documents\\chromedriver.exe");
        ChromeDriver driver = new ChromeDriver();
           
        // Maximize the browser
        driver.manage().window().maximize();
   
        // Launch Website
        driver.get("https://demoqa.com/alerts");
       
        // clicking on prompt button
        driver.findElement(By.xpath("//*[@id=\"confirmButton\"]")).click();
        Thread.sleep(3000);
       
        // accepting javascript alert
        Alert alert = driver.switchTo().alert();
        alert.accept();
         
        // clicking on prompt button
        driver.findElement(By.xpath("//*[@id=\"confirmButton\"]")).click();
        Thread.sleep(3000);
       
        // Rejecting javascript alert
        Alert alert1 = driver.switchTo().alert();
        alert1.dismiss();       
         
    }
 
}


Output:

The program will open the website and click on the confirmation alert button and accept the alert and again it click the alert button and decline the alert.

What are Popups in Selenium?

Selenium enables you to handle various types of popups and alerts that may appear during automated browsing, such as JavaScript alerts, modal dialogs, and browser notifications. You can switch to and interact with popup windows or accept/dismiss alerts using appropriate WebDriver methods.

How to Handle Popups in Selenium?

1. Switch to the Alert

Use driver.switchTo().alert(). This tells Selenium to focus on the alert instead of the main page.

2. Interact with the Alert

  1. Get the text: Use alert.getText() to read the message displayed in the alert.
  2. Accept the alert: Use alert.accept() to click the “OK” button (or equivalent).
  3. Dismiss the alert: Use alert.dismiss() to click the “Cancel” button (or equivalent).
  4. Enter text (for prompts): Use alert.sendKeys("text") to input text in prompts before accepting or dismissing.

Example:

Java




import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
 
public class AlertHandlingDemo {
 
    public static void main(String[] args) {
        // Set the path to the ChromeDriver executable
        System.setProperty("webdriver.chrome.driver", "D:\\driver\\Feb\\chromedriver.exe");//path will be changes as per your chrome browser saved where
 
        // Initialize ChromeDriver
        WebDriver driver = new ChromeDriver();
 
        // Navigate to the demoqa alerts page
        driver.get("https://demoqa.com/alerts");
 
        // Click the button that triggers an alert
        driver.findElement(By.id("alertButton")).click();
 
        // Switch to the alert
        Alert alert = driver.switchTo().alert();
 
        // Get and print the alert text
        String alertText = alert.getText();
        System.out.println("Alert text: " + alertText);
 
        // Accept the alert after getting the alert text
        alert.accept();
 
        // Close the browser
        driver.quit();
    }
}


Handling Web Dialog Box/Popup Window using Selenium

1. Navigate to the webpage “https://demoqa.com/alerts“.

2. Locate and click the button that triggers the alert dialog.

3. Wait for the alert to be present using WebDriverWait.

4. Switch to the alert and print its text.

5. Accept the alert (click OK).

6. Close the browser.

Java




import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
 
public class HandleWebDialogBox {
    public static void main(String[] args) {
        // Set the path to the ChromeDriver executable.
        System.setProperty("webdriver.chrome.driver", "D:\\driver\\Feb\\chromedriver.exe");
 
        // Initialize ChromeDriver.
        WebDriver driver = new ChromeDriver();
 
        // Navigate to the website.
        driver.get("https://demoqa.com/alerts");
 
        // Find and click the "Click me" button to trigger the dialog box.
        WebElement clickMeButton = driver.findElement(By.id("alertButton"));
        clickMeButton.click();
 
        // Explicitly wait for the alert to be present.
        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until(ExpectedConditions.alertIsPresent());
 
        // Switch to the alert.
        org.openqa.selenium.Alert alert = driver.switchTo().alert();
 
        // Get the text from the alert and print it.
        System.out.println("Alert Text: " + alert.getText());
 
        // Accept the alert (clicking OK).
        alert.accept();
 
        // Close the browser.
        driver.quit();
    }
}


Conclusion

This article taught us how to deal with alerts and pop-ups when running automated tests using Selenium. Alerts are those small message boxes that show up on the screen and can be either for giving information or asking for user input. We learned different ways to handle these alerts, like accepting them, dismissing them, getting their text, and sending keys to them. Also, we explored how Selenium helps us manage different types of pop-ups and alerts that might come up during automated browsing. The main idea is that knowing how to handle alerts and pop-ups is crucial for making our automated tests strong and reliable.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads