Handle Javascript 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!

Handle Web Links << Previous     ||     Next >>  Handle Multiple Browser Tabs



Follow Us

Quora Space | Facebook Page | Telegram Channel
Feel free to ask queries or share your thoughts in comments or email us.

Comments

Post a Comment

Popular posts from this blog

10 Best Demo Websites for Automation Testing Practice

Automate 'User Registration' of E-commerce Website using Selenium

Automate Browser Actions on Godaddy.com using Selenium

Automate E-Commerce Website using Selenium Webdriver