Alerts

What is Alert?
Alert is a dialogue box which displays informational message or warning message, or prompt you to input something, or ask you to confirm something etc etc. Depending upon from where the alert comes from we have:

  • Windows based alert pop ups, aka Alerts from OS
  • Web based alert pop ups

Webdriver can only handle web based alerts. To handle windows based pop ups, we have to turn to third party utilities for that.

How to Handle Alerts
First, we need to switch to the alert box:

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

Then we can dismiss the alert, or accept the alert or input something into the field in the box , or get the information displayed in the box using the following four methods of Alert interface:

1) void dismiss() – clicks on the “Cancel” button as soon as the pop up window appears.

Alert alert = driver.switchTo().alert();
alert.dismiss();
//or simply make above 2 lines into one:
driver.switchTo().alert().dismiss();

2) void accept() – clicks on the “Ok” button as soon as the pop up window appears.

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

3) String getText() – returns the text displayed on the alert box.

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

4) void sendKeys(String stringToSend) – enters the specified string into the alert box.

driver.switchTo().alert().sendKeys(“myUserNameblah”);