How to handle Alerts or Pop-Ups using Selenium Webdriver

In this post we will learn to handle alerts or popups with Selenium Webdriver using Java. Generally there are two types of alerts:
  1. Web based Alerts
  2. Window alerts
Out of these two only web based alerts can be handled using Selenium Webdriver. Window alerts cannot be handled using selenium webdriver, but there are other ways of handling the window alerts and we will discuss that strategy in next post. In this post we are going to handle web based alerts.

What is a web alert?
A web alert is generally a javascript based pop-up that appears on the screen. It commonly have a text message and two buttons which could be Yes or No, Accept or Dismiss, Ok or Cancel.




So there aren't much operations we can perform on an alert. Below are the commands used to handle web alerts:
  1. alert.accept()
  2. alert.dismiss()
  3. alert.getText()

/*  Alert handling   */

// Alert class object creation
Alert alert = driver.switchTo().alert();

// Below Code switches the control/focus of your execution to the alert
driver.switchTo().alert();

// Below command is used to accept the alert like click on Yes, Accept, Ok button
alert.accept();

// Below command is used to dismiss/reject the alert like click on No, Dismiss, Cancel button
alert.dismiss();



Sharing an example below in which, code snippet represents an example to validate Pop-up text.



// Expected Text
String expectedPopUpText = "Congratulations!";

// Expected text - getText() is the command to get text from a pop-up
String actualPopUpText = alert.getText();

// Print pop up text value before validation
System.out.println(actualPopUpText);

// Validate text
if expectedPopUpText == actualPopUpText){
    System.out.println("Pop Up Text matched.");
}
else{
    System.out.println("Pop Up Text does not matched.");
}


Thanks for reading, share your thoughts in comments. Happy Learning! :)



For list of  Selenium tutorials click here: Selenium Webdriver Tutorials Series
Author: Vaneesh Behl
Join Telegram channel of this blog at https://t.me/techlisticspace

Comments

Popular posts from this blog

List of Selenium Demo Websites for Practice

How to learn Selenium Webdriver on your own online