How to handle alerts

Today we will we see how we can handle alerts. Alerts are a special dialog box which appears on screen when user performs some action, to display some kind of information like error message or to take some extra information to proceed with the action. Alert dialog box are different from other regular windows as alerts are blocking in nature. It means if alert is present on screen then we cannot perform any other action on that page until we handle alerts. If we try to perform some action while alert is present, then webdriver will throw UnhandledAlertException: Modal dialog present exception.

There are mainly 3 types of alerts:

  • Simple Alert: Simple alerts are used to show an information to a user. This information may be related to error messages. Simple alerts contain a descriptive text and only one button. Generally, an OK button.

alert1

  • Confirmation Alert: Confirmation alerts are used to give user some information as well as a choice to accept or dismiss the alert. We can either accept this alert or we can dismiss it as it has both OK and Cancel button also.

alert2

  • Prompt Alert: Prompt alerts are used when some input text is required from user side to proceed with action. Prompt alerts contain a text box with accept and reject options like OK and Cancel buttons.

alert3

Selenium provides Alert interface to handle these kind of alerts. It is present in the org.openqa.selenium.Alert package. It provides us following methods to deal with alerts:

Note: We cannot directly access alerts. We need to first switch to alert window with the help of driver.switchTo.alert()

  • accept(): It is used to accept the SimpleConfirmation or Prompt alerts.

alert4

  • dismiss(): It is used for dismissing Confirmation or Prompt alerts.

alert5.jpg

  • getText(): It is used to get the text of the SimpleConfirmation or Prompt alerts.

alert6.jpg

  • sendKeys(): It is used to write some text to the alert. This method will take one argument of type string. It is used to pass some text data to Prompt alert.

alert7.jpg

That’s all about alerts. Hope you enjoyed this article.

Have a great Day!!!

Leave a comment