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");


How to Handle Alert in Selenium using Java?

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.

Similar Reads

Prerequisites

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? Install Eclipse IDE by referring to this article Eclipse IDE for Java Developers. Selenium: Download the Selenium latest stable version here. Web Driver: Download the Microsoft Edge Webdriver according to your version here....

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

How to Handle Alerts in Selenium?

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

Example of Alert Handling Using Selenium

...

What are Popups in Selenium?

...

How to Handle Popups in Selenium?

...

Handling Web Dialog Box/Popup Window using Selenium

...

Conclusion

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