JavaScript Alert in Selenium Webdriver

In the Web application, there are several JavaScript alert messages appear while executing the scripts or simply operating the application. So we need to know that how to handle JavaScript Alert in Selenium Webdriver.

Let’s take a scenario to handle JavaScript Alert message

Scenario:

  • Write a program to verify the JavaScript alert message for any validation of any overcount.
  • Click on OK button of JavaScript alert message.
  • Before clicking on Ok button, take the text message which is available in the alert message and print.

To handle the alert, we need to navigate from main window to alert. Then we can perform actions like either OK or Cancel.

Accept: It is to click OK on the alert message.

Dismiss: It is to click Cancel on the confirmation alert message.

Syntax:

driver.switchto().alert().accept();   // to click on OK button.

driver.switchto().alert().dismiss();  // to click on Cancel button.

 

Get Text: It is to take the text or label from the application where the webdriver is having the focus.

  • The written type of get text is String.

Syntax:

string str; 

str = driver.switchto().alert().gettext();   // to take the text message from the JavaScript alert

system.out.println(str);   // to print the text message

 

Please click here to read Automation Script Implementation in Webdriver

Please click here to read Browser Launch in Selenium Webdriver

Please click here to read Features of Selenium Webdriver

7 Thoughts on JavaScript Alert in Selenium Webdriver

Leave a Comment