1.Introduction

In this article, we’re going to illustrate how to handle alert or javascript Popup using selenium WebDriver.

2. Basics

Let’s get started by understanding what are these alerts or javascript popups.

  • Javascript Alert/popup is a notification/warning or message displayed on the User interface in box format to notify the user about some information or asks for permission to perform certain kind of operations.
  • Alert is a method in javascript and  displays an alert box with a specified message and an OK button.
  • what do we need to generate this alert on UI is simply open inspect window and click on console and type alert(“Hi this is an automation User!!”) . 
  • you will be able to see the popup similar to this:

3. Types of Alerts

  1. Simple Alert
  2. Confirmation Alert
  3. Prompt Alert

Let’s have a look at the first one:

Simple Alert:

This alert is called simple alert because it just notifies the user some information or warning with an “OK” or “Close” button as shown in the following image.

  • The above popup can not be handled with finding XPath of OK Button as we can not inspect or spy over this button.
  • So, to handle the above Popup, we need to look at Alert interface of selenium WebDriver

Alert Interface

  • Alert is an interface in selenium provide some methods to handle the alert
  • Syntax:
  • Alert alert= driver.switchTo().alert();
  • To handle the Alert, we first need to switch to alert using switchTo() method.
  • WebDriver interface contains method switchTo() which has return as interface and contains method alert() which has return type as Alert interface. 
  • RemoteAlert class in RemoteWebDriver class implement this Alert Interface
  • For complete code reference, visit over
  • RemoteWebDriver Implementation
  • alert() switches to the alert and return an alert reference and throw “NoAlertPresentException” if no alert exists.
  • Next, Let’s what actions we can perform once we switched to an alert

1.void dismiss(): This method clicks on the ‘Cancel’ button of the alert or dismiss the popup . It returns void.

Syntax:

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

2.void accept(): This method click on the ‘OK’ button of the alert and returns void

Syntax:

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

3.String getText() : This method captures the alert message and returns the String.

Syntax:

driver.switchTo().alert().getText();

4.void sendKeys(String Text):This method passes some data to alert input text and it returns void 

Syntax:

driver.switchTo().alert().sendKeys(“Text”);

Back to simple alert , let’s see following snippet code

 

Simple Alert

As can be seen, for simple Alert we just need to click on OK button and with one statement by switching to alert and accepting it we can achieve this scenario.

  • Confirmation Alert

  • Confirmation Alert is the alert which asks for confirmation from the user to perform certain actions.
  • User can opt for OK or Cancel button based on the requirements and also we can not inspect over this alert also.
  • Let’s see how it looks like

Following code snippet for the same:

package com.example.automation;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

/**
 * @author Mandeep Kaur
 * @Date 6 May,2020
 */
public class SeleniumConfig {
    public static void main(String[] args) throws InterruptedException {
        String path = System.getProperty("user.dir");
        System.setProperty("webdriver.chrome.silentOutput", "true");
        System.setProperty("webdriver.chrome.driver", path + "/chromedriver");
        WebDriver driver = new ChromeDriver();

        driver.get("https://testuserautomation.github.io/Alerts/");
        driver.findElement(By.xpath("//button[2]")).click();

       Alert alert = driver.switchTo().alert();
       System.out.println(alert.getText());
        //For OK button in alert, accept the PopUp
        alert.accept();
        Thread.sleep(2000);
        WebElement text =driver.findElement(By.xpath("//*[@id='demo']"));
        //verify the text after accepting the popUp
        System.out.println(text.getText());
        driver.close();

    }
}

As shown in the code, we have accepted the alert and verify the text we got after running the above piece of code and we get output similar to:

  • Prompt Alert

  • This Alert is to get input from the user in the form of text.
  • From the above methods, we have to use alert.sendKeys() method to send the text in an alert
  • After entering the input, the user can press the OK or Cancel Button.
  • Let’s prompt Alert on UI

 

prompt Alert

Now , see the code snippet for the same:

package com.example.automation;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;


/**
 * @author Mandeep Kaur
 * @Date 6 May,2020
 */
public class SeleniumConfig {
    public static void main(String[] args) throws InterruptedException {
        String path = System.getProperty("user.dir");
        System.setProperty("webdriver.chrome.silentOutput", "true");
        System.setProperty("webdriver.chrome.driver", path + "/chromedriver");
        WebDriver driver = new ChromeDriver();

        driver.get("https://testuserautomation.github.io/Alerts/");
        driver.findElement(By.xpath("//button[3]")).click();

       Alert alert = driver.switchTo().alert();
       System.out.println(alert.getText());
       //Send Text to the Alert
        alert.sendKeys("TestAutomationUser!!");
        //For OK button in alert, accept the PopUp
        alert.accept();
        Thread.sleep(2000);
        WebElement text =driver.findElement(By.xpath("//*[@id='test']"));
        //verify the text after accepting the popUp
        System.out.println(text.getText());
        driver.close();

    }
}

We can see that here before accepting the Popup, we have sent the “TestAutomationUser” to the alert and verified the text after we accepted the popup and output will be like following

 
 
 
Do we have some other pop ups as well? 
Answer is YESSS…
 
 
Now, there are few other Popups such as Authentication popup and window-based  popup like file Upload , we need to have strong understanding to tackle such popups :
Let’s quickly discuss about Basic Authentication Popup First: 
 
1) Basic Authentication popup : It asks user to enter username and password to the popup  when the browser gets launched and it looks like something :
As can be comprehended from the above snapshot that we need to pass username and password and we can’t spy over this popup.
Let’s look at below code snippet to handle this popup

 

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

/**
* @author Mandeep Kaur
* @Date 6 May,2020
*/
public class SeleniumConfig {
public static void main(String[] args) throws InterruptedException {
String path = System.getProperty(“user.dir”);
System.setProperty(“webdriver.chrome.silentOutput”, “true”);
System.setProperty(“webdriver.chrome.driver”, path + “/chromedriver”);
WebDriver driver = new ChromeDriver();

//send username : admin and password: admin in url before launching the browser
driver.get(“https://admin:admin@the-internet.herokuapp.com/basic_auth”);

//validate if popup is closed successfully and capture the text

WebElement successMessage = driver.findElement(By.xpath(“//div[@class=’example’]//p”));

System.out.println(successMessage.getText());

}
}

It’s pretty clear from the above code that we just need to pass the username and password in the URL and after “@” the complete URL, after that, we can verify the success message, this is how we can achieve our goal.

2) Window-based File Upload popup :

Window-based popup interacts with window operations, selenium doesn’t provide direct support to handle this type of popup  but there is a workaround to operate on such cases. let’s look down to understand this in detail:

Window/ Mac-based popup appears like this once you click on choose file:

Let’s see the code to handle this popup:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

/**
* @author Mandeep Kaur
* @Date 6 May,2020
*/
public class SeleniumConfig {
public static void main(String[] args) throws InterruptedException {
String path = System.getProperty(“user.dir”);
System.setProperty(“webdriver.chrome.silentOutput”, “true”);
System.setProperty(“webdriver.chrome.driver”, path + “/chromedriver”);
WebDriver driver = new ChromeDriver();

//launch the url
driver.get(“https://the-internet.herokuapp.com/upload”);

//inspect over the choose file element and send File from your directory to it
WebElement uploadFile = driver.findElement(By.xpath(“//input[@name=’file’]”));
uploadFile.sendKeys(“/Users/Documents/index.html”);

//click on upload button
driver.findElement(By.xpath(” //input[@class=’button’]”)).click();

//verify the message
WebElement successMessage= driver.findElement(By.xpath(“//div[@class=’example’]//h3”));
System.out.println(successMessage.getText());

driver.close();
}
}

Explanation:

1. We first need to inspect over choose file Button and capture XPath, HTML to look like below where it should have <input> tag and type should be file:

<input id=”file-upload” type=”file” name=”file” xpath=”1″>

 

2. Next, need to send File to upload using sendKeys(String fileNameWithExtension);

3. It will upload the file and we can verify the file is uploaded or not by capturing the success message like following:

4. Conclusion

In this write-up, we have learnt about javascript alerts, a few other types of popups and various ways to handle all these popups.

 

That’s all for this post, hope you have learnt about PopUps 🙂

 

Cheers!!

Naveen AutomationLabs

 

Blog Contributors:

Author:  Mandeep Kaur
Mandeep, having 5+ years of Testing experience in automation using Selenium (Java). Expertise in API and Performance testing using JMeter.
https://www.linkedin.com/in/mandeepkaur93
 
Reviewer: Naveen Khunteta 
https://www.linkedin.com/in/naveenkhunteta