Handling different types of alerts & user authentication in selenium

Alerts are basically popup box that takes the focus away from the current browser screen and forces you to read the alert message and do some action,
Once you take any action (accept or dismiss), it allows to resume performing the task on browser.

There are basically 3 types of alerts
Alert box, Confirm box, and Prompt box.

We will see how to handle each of these diff types of alerts in selenium


A simple alert:

in this either you can accept or dismiss an alert


Alert exception handling

We can handle the alert exception (org.openqa.selenium.NoAlertPresentException), this exception appears when we try to switch to an alert, but alert not found.

Let’s make a failed scenario, where we are trying to switch to alert but alert not appearing.

Note –

If you are using webDriverWait for an alert, then TimeoutException appears if time out.

Here is the detail of code implementation for both the exceptions to handle an alert.


Prompt alert

Here we can enter text in alert textbox, check the checkboxes and can accept / dismiss…

If you want to handle the “prevent this page…” mark box on the dialog, then we can use Robot class in java to send key events to the alert like TAB, SPACE BAR to check the checkbox.

Note : This below code even explains, the usage of Robot java class in selenium.


Username and password alert


Some sites pops up alerts to enter username and password, these fields can’t be identified by browser locators (plugins such as firebug for ff or F12 for IE),in this case we can pass the username and password while launching the browser,

Simple solution is to pass username and password while launching browser.


Confirm alert

Either you can accept and dismiss the alert, if u click on “prevent this from…” checkbox, you won’t get the alert again for that browser instance…

Chose proper alert handling method from above, and handle alerts from your testing site.
Short links – bit.ly/qav-selalerts 

Content posted is based on learning or working experience,
Share the post with others if find useful,
Any queries?, leave comments or discuss on our facebook:qavalidation.com, Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *