Types of alerts:
Simple alert with message
Alert with input feature
How to handle Alert in Selenium WebDriver ?
Alert can be handled by switching to the alert.First we need to switch to the alert using .switchTo() method, it returns an Alert type object.Using the alert object variable we can accept/dismiss/get text of the alert.If there is no alert currently present, and you invoke this switchTo() method, it throws back a NoAlertPresentException.
Syntax:
Alert interface provides the below few methods which are widely used in Selenium Webdriver.
1) void dismiss() // To click on the 'Cancel' button of the alert.
driver.switchTo().alert().dismiss();
or
Alert alert = driver.switchTo().alert();
alert.dismiss();
2) void accept() // To click on the 'OK' button of the alert.
driver.switchTo().alert().accept();
or
Alert alert = driver.switchTo().alert();
alert.accept();
3) String getText() // To capture the alert message.
driver.switchTo().alert().getText();
or
Alert alert = driver.switchTo().alert();
String data=alert.getText();
4) void sendKeys(String stringToSend) // To send some data to alert box.
driver.switchTo().alert().sendKeys("Text");
or
Alert alert = driver.switchTo().alert();
alert.sendKeys("any text");
The Alert interface contains a number of methods to execute different actions. The following list discusses them one after the other:
- void accept(): This is equivalent to the OK button action on the dialog.The corresponding OK button actions are invoked when the accept() action is taken on a dialog.
- void dismiss():This is equivalent to clicking on the CANCEL action button.
- java.lang.String getText(): This will return the text that appears on the dialog. This can be used if you want to evaluate the text on the modal dialog.
- void sendKeys(java.lang.String keysToSend): This will allow the us to type in some text into the alert if the alert has some provision for it.