Handling Javascript Alerts/Popups In Selenium Webdriver
Hello Folks,
In last post, we have seen handing of website popups in selenium webdriver.
In this post, we will see how to handle JavaScript popups in selenium webdriver.
Types of JavaScript popups:
There are three types of popups in JavaScript which are given below:
- Alert popup
- Confirm popup
- Prompt popup
Alert popup:
- It is a simple popup which shows some information to user in a small box within browser area.
- It will have one “OK” button and close button.
- Since, it is just a information box so OK button and close button will have similar functionality.
- Popup will be disappeared when user clicks on either OK button or close button.
- You can not inspect alert popup.
- Without handling alert popup, you can not proceed further.
JavaScript code to create a alert popup:
Since you can not inspect alert popup, you can not handle it with selenium webdriver directly. So we need to use Alert interface.
Alert Interface:
Alert is an interface in selenium library. It has below methods in it:
- accept() : To click on OK button on popup.
- dismiss(): To click on close/cancel button of popup.
- getText(): To get text present on popup.
- sendKeys(java.lang.String keysToSend): To type on prompt popup.
- authenticateUsing(Credentials credentials) (Beta method)
setCredentials(Credentials credentials)
(Beta method)
A private class EventFiringAlert implements Alert interface.
Handling of alert popup in selenium webdriver:
To handle alert popup, first we need to switch to alert using switchTo() method. Syntax is as below:
Alert alert= driver.switchTo().alert();
- alert() switches to the currently active popup for particular driver instance and return an Alert reference. It will throw NoAlertPresentException if no alert is present.
Java code:
Output: Alert text is:I am alert popup and you can not inspect me. You need to handle me using Alert interface. Alert closed successfully afetr accept.
Alert closed successfully after dismiss.