How to Handle Alerts/Popups in Selenium WebDriver – Selenium Tutorial #16

Efficient Ways to Handle Windows and Web-based Alerts/Popups in Selenium WebDriver:

In the previous tutorial, we focused our discussion on different types of waits provided by the WebDriver. We also discussed about various types of navigation options available in WebDriver.

Moving ahead in the Selenium WebDriver Tutorials, we will discuss about different types of alerts available while testing web applications and their handling strategies.

Handling alerts popups in selenium

There are two types of alerts that we would be focusing on majorly:

  1. Windows-based alert pop-ups
  2. Web-based alert pop-ups

As we know that handling windows based pop-ups is beyond WebDriver’s capabilities, thus we would exercise some third-party utilities to handle window pop-ups.

Handling pop up is one of the most challenging pieces of work to automate while testing web applications. Owing to the diversity in types of pop ups complexes the situation even more.

What is Alert box/ Pop up box/ confirmation Box/ Prompt/ Authentication Box?

It is nothing but a small box that appears on the display screen to give you some kind of information or to warn you about a potentially damaging operation or it may even ask you for the permissions for the operation.

Example: Let us consider a real-life example for a better understanding; Let us assume that we uploaded a photograph on any of these popular social networking sites. Later on, I wish to delete the uploaded photograph. So in order to delete, I clicked on the delete button. As soon as I click on the delete button, the system warns me against my action, prompting – Do you really want to delete the file? So now we have an option to either accept this alert or reject it.

So ahead of the session, let’s see how do we reject or accept the alerts depending on their types. Starting with the web-based pop ups.

Web-Based Popups

webdriver alerts 1

Let us see how do we handle them using WebDriver.

Handling web-based pop-up box

WebDriver offers the users with a very efficient way to handle these pop ups using Alert interface.

There are the four methods that we would be using along with the Alert interface.

1) void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the pop up window appears.
2) void accept() – The accept() method clicks on the “Ok” button as soon as the pop up window appears.
3) String getText() – The getText() method returns the text displayed on the alert box.
4) void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.

Let us move ahead and look at the actual implementation.

Explanation of Application under Test

We have designed a web page in a way to include a few fundamental types of web elements. This is the same application we introduced while discussing Select class earlier in this series.

  • Hyperlink: The two hyperlinks namely “Google” and “abodeQA” have been provided that re-directs the user to “http://www.google.com/” and “http://www.abodeqa.com/” respectively on the click event.
  • Dropdown: The three hyperlinks have been created for selecting colours, fruits and animals with a value set to default.
  • Button: A “try it” button has been created to show up the pop up box having OK and Cancel buttons upon click event.

(Click on image to view enlarged)

 

webdriver alerts 2

Subsequent is the HTML code used to create the above-mentioned webpage:

<!DOCTYPE html></pre>
<html>
<head><title> Testing Select Class </title>
<body>
<div id="header">
<ul id="linkTabs">
<li>
<a href="https://www.google.com/">Google</a>
</li>
<li>
<a href="http://abodeqa.wordpress.com/">abodeQA</a>
</li>
</ul>
</div>
<div class="header_spacer"></div>
<div id="container">
<div id="content" style="padding-left: 185px;">
<table id="selectTable">
<tbody>
<tr>
<td>
<div>
<select id="SelectID_One">
<option value="redvalue">Red</option>
<option value="greenvalue">Green</option>
<option value="yellowvalue">Yellow</option>
<option value="greyvalue">Grey</option>
</select>
</div>
</td>
<td>
<div>
<select id="SelectID_Two">
<option value="applevalue">Apple</option>
<option value="orangevalue">Orange</option>
<option value="mangovalue">Mango</option>
<option value="limevalue">Lime</option>
</select>
</div>
</td>
<td>
<div>
<select id="SelectID_Three">
<option value="selectValue">Select</option>
<option value="elephantvalue">Elephant</option>
<option value="mousevalue">Mouse</option>
<option value="dogvalue">Dog</option>
</select>
</div>
</td>
</tr>
<tr>
<td>

<!DOCTYPE html>
<html>
<body>
<p>Click the button to display a confirm box.</p>
<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
confirm("Press a button!");
}
</script>
</body>
</html>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>

Scenario to be automated

  1. Launch the web browser and open the webpage
  2. Click on the “Try it” button
  3. Accept the alert
  4. Click on the “Try it” button again
  5. Reject the alert

WebDriver Code using Select Class

Please take a note that for script creation, we would be using “Learning_Selenium” project created in the former tutorial.

Step 1: Create a new java class named as “DemoWebAlert” under the “Learning_Selenium” project.
Step 2: Copy and paste the below code in the “DemoWebAlert.java” class.

Below is the test script that is equivalent to the above-mentioned scenario.

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

/**
* class description
*/

public class DemoWebAlert {
                WebDriver driver;
                /**
                * Constructor
                */
                public DemoWebAlert() {                            
                }

                /**
                * Set up browser settings and open the application
                */

                @Before
                public void setUp() {
                                driver=new FirefoxDriver();
                                // Opened the application
                                driver.get("file:///F:/Work/Selenium/Testing-Presentation/DemoWebPopup.htm");
                                driver.manage().window().maximize();
                }

                /**
                * Test to check Select functionality
                * @throws InterruptedException
                */

                @Test
                public void testWebAlert() throws InterruptedException {                          
                                // clicking on try it button
                                driver.findElement(By.xpath("//button[contains(text(),'Try it')]")).click();
                                Thread.sleep(5000);

                                // accepting javascript alert
                                Alert alert = driver.switchTo().alert();
                                alert.accept();

                                // clicking on try it button
                                driver.findElement(By.xpath("//button[contains(text(),'Try it')]")).click();
                                Thread.sleep(5000);

                                // accepting javascript alert
                                driver.switchTo().alert().dismiss();

                                // clicking on try it button
                                driver.findElement(By.xpath("//button[contains(text(),'Try it')]")).click();
                                Thread.sleep(5000);

                                // accepting javascript alert
                                System.out.println(driver.switchTo().alert().getText());
                                driver.switchTo().alert().accept();
                }

                /**
                * Tear down the setup after test completes
                */

                @After
                public void tearDown() {             
                    driver.quit();
                }
} 

Code Walk-through

Import Statements

Import org.openqa.selenium.Alert – Import this package prior to the script creation The package references to the Alert class which is required to handle the web-based alerts in WebDriver.

Object Creation for Alert class
Alert alert = driver.switchTo().alert();

We create a reference variable for Alert class and references it to the alert.

Switch to Alert
Driver.switchTo().alert();
The above command is used to switch the control to the recently generated pop up window.

Accept the Alert
alert.accept();
The above command accepts the alert thereby clicking on the Ok button.

Reject the Alert
alert.dismiss();
The above command closes the alert thereby clicking on the Cancel button and hence the operation should not proceed.

Window Based Pop-Ups

webdriver alerts 3

At times while automating, we get some scenarios, where we need to handle pop ups generated by windows like a print pop up or a browsing window while uploading a file.

Also read =>> How to handle file upload in Selenium

Handling these pop-ups have always been a little tricky as we know Selenium is an automation testing tool which supports only web application testing, that means, it doesn’t support windows based applications and window alert is one of them. However Selenium alone can’t help the situation but along with some third-party intervention, this problem can be overcome.

There are several third-party tools available for handling window based pop-ups along with the selenium.

So now let’s handle a window based pop up using Robot class.

Robot class is a java based utility which emulates the keyboard and mouse actions.

Before moving ahead, let us take a moment to have a look at the application under test (AUT).

Explanation of Application under Test

As an application under test, we would be using “gmail.com”. I believe the application doesn’t require any more introductions.

Scenario to be automated

  1. Launch the web browser and open the application – “gmail.com”
  2. Enter valid username and password
  3. Click on the sign in button
  4. Click on the compose button
  5. Click on the attach icon
  6. Select the files to be uploaded with the window based pop up.

WebDriver Code using Robot Class

Please take a note that for script creation, we would be using “Learning_Selenium” project created in the former tutorial.

Step 1: Create a new java class named as “DemoWindowAlert” under the “Learning_Selenium” project.
Step 2: Copy and paste the below code in the “DemoWindowAlert.java” class.

Below is the test script that is equivalent to the above-mentioned scenario.

 import java.awt.Robot;</pre>
import java.awt.event.KeyEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class DemoWindowAlert {
WebDriver driver;
@Before

public void setUp()
{
driver=new FirefoxDriver();
driver.get("https://gmail.com");
driver.manage().window().maximize();
}

@Test
public void testWindowAlert() throws Exception{

// enter a valid email address
driver.findElement(By.id("Email")).sendKeys("TestSelenium1607@gmail.com");

// enter a valid password
driver.findElement(By.id("Passwd")).sendKeys("TestSelenium");

// click on sign in button
driver.findElement(By.id("signIn")).click();
Thread.sleep(30000);

// click on compose button
driver.findElement(By.xpath("//div[@class='z0']//div[contains(text(),'COMPOSE')]")).click();

// click on attach files icon
driver.findElement(By.xpath("//div[contains(@command,'Files')]//div[contains(@class,'aaA')]")).click();

// creating instance of Robot class (A java based utility)
Robot rb =new Robot();

// pressing keys with the help of keyPress and keyRelease events
rb.keyPress(KeyEvent.VK_D);
rb.keyRelease(KeyEvent.VK_D);
Thread.sleep(2000);

rb.keyPress(KeyEvent.VK_SHIFT);
rb.keyPress(KeyEvent.VK_SEMICOLON);
rb.keyRelease(KeyEvent.VK_SEMICOLON);
rb.keyRelease(KeyEvent.VK_SHIFT);

rb.keyPress(KeyEvent.VK_BACK_SLASH);
rb.keyRelease(KeyEvent.VK_BACK_SLASH);
Thread.sleep(2000);

rb.keyPress(KeyEvent.VK_P);
rb.keyRelease(KeyEvent.VK_P);

rb.keyPress(KeyEvent.VK_I);
rb.keyRelease(KeyEvent.VK_I);

rb.keyPress(KeyEvent.VK_C);
rb.keyRelease(KeyEvent.VK_C);
Thread.sleep(2000);

rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(2000);
}

@After
public void tearDown()
{
driver.quit();
}
} 

Code Walk-through

Import Statements

import java.awt.Robot – Import this package prior to the script creation The package references to the Robot class in java which is required simulate keyboard and mouse events.

import java.awt.event.KeyEvent – The package allows the user to use keyPress and keyRelease events of a keyboard.

Object Creation for Robot class
Robot rb =new Robot();
We create a reference variable for Robot class and instantiate it.

KeyPress and KeyRelease Events
rb.keyPress(KeyEvent.VK_D);
rb.keyRelease(KeyEvent.VK_D);

The keyPress and keyRelease methods simulate the user pressing and releasing a certain key on the keyboard respectively.

Conclusion

In this tutorial, we tried to make you acquainted with the WebDriver’s Alert class that is used to handle web-based pop ups. We also briefed you about the Robot class that can be used to populate the value in the window based alert with the help of keyPress and keyRelease events.

Article summary:

  • Alerts are a small box that appears on the display screen to give you some kind of information or to warn you about a potentially damaging operation or it may even ask you for the permissions for the operation.
  • There are popularly two types of alerts
    • Windows-based alert pop ups
    • Web-based alert pop ups
  • Prior to the actual scripting, we need to import a package to be able to create a WebDriver script for handling a drop-down and making the Select class accessible.
  • WebDriver offers the users with a very efficient way to handle these pop ups using Alert interface.
  • void dismiss() – The dismiss() method clicks on the “Cancel” button as soon as the pop up window appears.
  • void accept() – The accept() method clicks on the “Ok” button as soon as the pop up window appears.
  • String getText() – The getText() method returns the text displayed on the alert box.
  • void sendKeys(String stringToSend) – The sendKeys() method enters the specified string pattern into the alert box.
  • Handling window based pop-ups have always been a little tricky as we know Selenium is an automation testing tool which supports only web application testing, that means, it doesn’t support windows based applications and window alert is one of them.
  • Robot class is a java based utility which emulates the keyboard and mouse actions and can be effectively used to handling window based pop up with the help of keyboard events.
  • The keyPress and keyRelease methods simulate the user pressing and releasing a certain key on the keyboard respectively.

Next Tutorial #17: In the upcoming tutorial, we would discuss about the various other commonly used WebDriver commands. We would shed light on topics like exception handling and iframe handling. We would also discuss about the get commands provided in WebDriver.

We would explain these topics with quick examples in order to make them understandable for the readers to exercise these concepts in their day to day scripting.

Note for the Readers: Till then, stay tuned and automate the web pages having the web based and window based pop ups using WebDriver utility – “Alert class” and Java utility – “Robot Class”.

Feel free to post your queries/comments about this or any other previous tutorials in comments below.

Recommended Reading