Learn Selenium
上QQ阅读APP看书,第一时间看更新

Handling alerts   

Apart from switching between windows and frames, you may have to handle various modal dialogs in a web application. For this, WebDriver provides an API to handle alert dialogs. The API for that is as follows:

Alert alert()

The preceding method will switch to the currently active modal dialog on the web page. This returns an Alert instance, where appropriate actions can be taken on that dialog. If there is no dialog currently present, and you invoke this API, it throws back a NoAlertPresentException.

The Alert interface contains a number of APIs 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 developer to type in some text into the alert if the alert has some provision for it.