Handling Alerts in Selenium
In our daily lives, Alerts are commonly used to show a sign of danger or threat, most of the time with the intention to avoid or to be dealt with. Similarly Alert in Selenium notifies the user with some specific information or error, asks for permission to perform certain tasks and it also provides warning messages as well. Software Alert is pop up window that comes up on screen.
There are many user actions that can result in an alert on screen. For example, a user clicked on a button that displayed a message or may be when user entered a form, HTML page asked for some extra information. Alerts are different from regular window. It is small message box that appears on the screen with relevant messages.
The main difference is that alerts are blocking in nature. Alerts won’t allow any action on the underlying webpage if they are present. If an alert is present on the webpage and user tries to access any of the element in the underlying page, the following exception occurs:
UnhandledAlertException: Modal dialog present
Types of Alerts:
· Window based alert
· Web based alert
Selenium supports only web based applications, Window based alerts are not supported by selenium. However third party tools like ‘AutoIt’ and ‘Robot’ are used to handle window based alerts.
Types of Web Based Alert:
1. Simple Alert:
Simple alert displays the valid information to user along with an OK button.
2. Confirmation Alert
Confirmation alert asks the user for confirmation of messages. It has two buttons, OK and Cancel with the message which needs a user action whether to accept or reject the alert message.
3. Prompt Alert
Prompt alert takes input from user with OK button to accept the input and Cancel button to close the alert window.
Selenium provides an interface called Alert, which is present in org.openqa.selenium.Alertpackage.
The following methods are available in Alert interface:
accept(): To accept the alert
dismiss(): To dismiss the alert
getText(): To get the text of the alert
sendKeys(): To send some data to alertbox
Sample code to capture alerts in Selenium
Code Snippet for Simple Alert:
Code Snippet for Confirmation Alert
Code Snippet for Prompt Alert
Note: If there is no alert and if you try to switch to an alert then selenium throws a “NoAlertPresentException”.
The brief description about alerts and the code for practice website is given above. Happy Testing 'Alerts in Selenium'!!