How to handle Alerts/Pop-Ups in Selenium

In this tutorial, we will learn How to handle Alerts/Pop-Ups in Selenium web driver automation.

Alerts:

Alert is a notification message box that displays options to act on it or it will give some kind of information. It may be also used for warning pop-ups when you do specific action on a web page.

How to identify Alerts:

Users cannot do any further actions on the web page until you act on it and you cannot inspect it.

Types of Alerts:

  1. Simple Alert:

In a simple alert, it will display some information or warning and Ok button to click on it.

Simple Alert -How to handle Alerts/Pop-Ups in Selenium

2.Prompt Alert:

In a prompt alert, it will ask some information to enter data in text field along with ‘Ok’ and ‘Cancel’ button

Prompt Alert - How to handle Alerts/Pop-Ups in Selenium

3.Confirmation Alert:

In confirmation alert, it will ask permission to act on it.

Confirmation Alert - How to handle Alerts/Pop-Ups in Selenium

Whenever we get any alerts in a web-based application then we cannot do any action on a web page and we need to handle these alerts to run the test case smoothly. To handle alerts we have to click options present in alerts.

To handle alerts need to initialize alert interface and using alert methods we can handle alerts.

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

            i. dismiss(): By using this method we can click on the cancel button

                        alrt.dismiss();

            ii. accept(): By using this method we can click on OK button

                        alrt.accept();

            iii. getText(): By using this method we can retrieve alert message

                        alrt.getText();

            iv. sendKeys(): By using this method we can enter data into alert prompt

                        alrt.sendKeys(“data”);

Please find the below sample script to know how to handle Alerts/Pop-Ups in Selenium

Note: I have used the chrome driver. if you want to download the driver you can get from selenium official website or simply you can click here.

To inspect and practice sample automation web page you can click here

Please provide your comments or you need more info on this. Thank you 👍.

You May Also Like

About the Author: Azgar Khan

Leave a Reply

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