How to handle Javascript alert using Selnium WebDriver

In this post, we will discuss that how to handle JavaScript alert using Selenium WebDriver.
In website, you may have seen Java script alert which pops up for some cases. For example, While submitting invalid card details, you may get Java script alert explaining about the incorrect entered values.

There are many cases you may encounter while doing automation where you will see these JavaScript alerts.

Selenium WebDriver has the capabilities to handle these alerts via simple commands.

Selenium Provides Alert API to handle Java script alert.

Using Alert API, you can perform following actions on JavaScript alert.

accept() – Accept the alert
dismiss() – Reject the alert
getText() – Read the text displayed on alert
sendKeys() – To write text into InputBox displayed on alert

NOTE : When you initialize WebDriver object, you get a control of the WebElements displayed on currently opened web page. But as soon as JavaScript alert pops up after some actions, your WebDriver object can’t access it until you switch the control of your WebDriver object to that alert.

Command to switch the control to Java script alert :

You have to import a following package in your script for Alert APIimport org.openqa.selenium.Alert

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

Sample code to accept the alert

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

Alert

Sample code to reject the alert

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

Alert

Sample code to write the text on alert

Alert alert = driver.switchTo().alert();
alert.sendKeys("Testing alert");
alert.accept();

Alert

Sample code to read the text displayed on alert

Alert alert = driver.switchTo().alert();
String text = alert.getText();
alert.accept();

Alert

If you really like the information provided above, please don’t forget to like us on Facebook, you can also leave the comment.

Leave a Reply

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