How to Handle Alerts and Popup in Selenium using Java

                       Handling Alerts and Popups in Selenium 

What is Alert in Selenium Webdriver?
Alerts in Selenium web driver are small message boxes that notify the user of some notification or message or ask some permission to perform certain kinds of task. it is also used for warning purposes or to enter some details in the alert box as well.

Types of Alerts in Selenium Webdriver 
Alerts in selenium are categorized into three parts.
  • Simple Alert 
  • Confirmation Alert 
  • Prompt Alert 

How to Click on The "Cancel" Button of the Alert?
In selenium webdriver to click on the cancel button of alert we use the dismiss method .dismiss method is a predefined method of the selenium alert class.

Selenium Code  

// How to click on cancel button
Alert alt = driver.switchTo().alert();
System.out.println(" cancel button clicked successfully");

How to Click on the "Ok" Button of the alert?

In selenium to click on the ok button of the alert we use accept method. 

Selenium code

//How to Click on ok button
Alert alt= driver.switchTo().alert();
System.out.println(" OK button clicked successfully");

How To Get or Capture an Alert Message in Selenium?

In Selenium to get the message of alert we use the get text method.

Selenium Code 

//How to get text from alert window 
String altmsg=driver.switchTo().alert().getText();

//To verify the message 

if(altmsg.contains("Do you really want to delete this Customer?")) 
System.out.println("valid Message ");
else {
System.out.println("invalid Message");

How To Enter the Data in the Text Box on Alert?

sendkeys method in selenium is used to send data to the alert box.

Selenium Code -
 //How to handle promt alert
Alert alt = driver.switchTo().alert();

Hope !!! The above tutorial on handling alerts and popups in Selenium is helpful for you ...

QA acharya

How to handle alerts in Selenium using java

Post a Comment