9x. WebDriver – Handling alerts/pop-up boxes

Hiya enthusiasts! Wondering why Alert interface exists in Selenium WebDriver? Well, my friend, look no further than this post for the information you seek. We are going to talk all about popup boxes which are basically of three kinds – Alert box, Confirm box and Prompt box. As always we have our Demo Site to illustrate these concepts.

Sticky Note:

In case a popup box appears on the web page, the user cannot perform any action on the underlying page as long as the alert isn’t accepted or dismissed. Beware, you might bump into “UnhandledAlertException: Modal dialog present” if you try to access any element on the web page with an alert.

1. Alert box

A simple alert box is usually used to pass on information to the user or to give some warning. The user cannot proceed further unless ‘OK’ button is clicked.

JavaScript code:

window.alert("This is a simple alert box! \nYou can't escape from me until you click 'OK'!");

Alert Box2. Confirm box

A confirm box provides two options to the user in order to verify/accept or dismiss something. The user has to click either ‘OK’ or ‘Cancel’ to proceed. Boolean values are returned by the confirm popup box. It returns a true when the user clicks on ‘OK’ and it returns a false when clicked on ‘Cancel’.

JavaScript code:

window.confirm("Click 'OK' or 'Cancel'.");

Confirm Box

3. Prompt box

A prompt box is used in circumstances when we want the user to enter a value. Similar to other alert boxes, the user has to click either an ‘OK’ or a ‘Cancel’ button inorder to proceed further. Prompt box returns the input value when clicked on ‘OK’ and returns a null if clicked on ‘Cancel’.

JavaScript code:

window.prompt("Which Selenium Tool do you like the most?","e.g. Selenium IDE");

Prompt Box

Hope you have a clear understanding of the different types of web-based pop-ups now.

Handling pop-up boxes:

Selenium WebDriver hasn’t offered us any way to handle these popup boxes. Did you believe what I just said?

Ha! I know there is no fooling you! WebDriver always has answers to all our problems. The Alert Interface which comes with org.openqa.selenium.Alert package!!

Some of the most useful methods that are frequently used are,

1. WebDriver switchTo()

This is the method used to switch from the main window to the popup or the alert that is displayed.

driver.switchTo().alert();

2. void accept()

This method is used to accept the alert. It clicks on the ‘OK’ button.

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

3. void dismiss()

This method is used to dismiss the alert. It clicks on the ‘Cancel’ button.

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

4. String getText()

To get the text displayed in the pop-up box, this method is used and it returns the text as a String.

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

5. void sendKeys(String textToSend)

This method is used to enter a particular String in the displayed popup box, usually a prompt box.

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

Scenario

Let us see a test case implementing these methods to get a good grasp of the concepts at a deeper level,

  1. Open Firefox browser
  2. Navigate to the demo site
  3. Locate ‘Alert Box’ button using id
  4. Click the button for alert box popup
  5. Get the displayed text of the alert popup and print it to console
  6. Accept the alert popup
  7. Locate ‘Confirm Box’ button using id
  8. Click the button for confirm box popup
  9. Print the alert message to console
  10. Dismiss the confirm popup
  11. Locate ‘Prompt Box’ button using XPath
  12. Click the button for prompt box popup
  13. Get the prompt box message and display it to console
  14. Accept the promt popup
  15. Verify Eclipse IDE console output screen and JUnit pane for success result

JUnit code for this scenario is,

package com.blog.junitTests;

import java.util.concurrent.TimeUnit;

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.WebElement; 
import org.openqa.selenium.firefox.FirefoxDriver;

public class PopupBoxes {
    // Declaring variables
    private WebDriver driver;
    private String baseUrl;

    @Before
    public void setUp() throws Exception {
        // Selenium version 3 beta releases require system property set up
        System.setProperty("webdriver.gecko.driver", "E:\\Softwares\\"
                + "Selenium\\geckodriver-v0.10.0-win64\\geckodriver.exe");
        // Create a new instance for the class FirefoxDriver
        // that implements WebDriver interface
        driver = new FirefoxDriver();
        // Implicit wait for 5 seconds
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        // Assign the URL to be invoked to a String variable
        baseUrl = "https://chandanachaitanya.github.io/selenium-practice-site/";
    }

    @Test
    public void testPageTitle() throws Exception {
        // Open baseUrl in Firefox browser window
        driver.get(baseUrl);
        // Locate 'Alert Box' button using id
        WebElement alertBoxBtn = driver.findElement(By.id("alertBox"));
        // Click the button for alert box popup
        alertBoxBtn.click();
        // Switch the control to 'Alert Box' popup
        Alert alertPopUp = driver.switchTo().alert();
        // Print the alert message to console
        System.out.println("Alert Box message: " + alertPopUp.getText());
        // Accept the alert popup
        alertPopUp.accept();
        
        Thread.sleep(5000);
        
        // Locate 'Confirm Box' button using id
        WebElement confirmBoxBtn = driver.findElement(By.id("confirmBox"));
        // Click the button for confirm box popup
        confirmBoxBtn.click();
        // Switch control to 'Confirm Box' popup
        Alert confirmPopUp = driver.switchTo().alert();
        // Dismiss the popup
        confirmPopUp.dismiss();
        System.out.println("Confirm box popup dismissed!");
        
        Thread.sleep(5000);
        
        // Locate 'Prompt Box' button using XPath
        WebElement promptBoxBtn = driver.findElement(By.xpath("/html/body/form/div[4]/div[3]/button"));
        // Click the button for prompt box popup
        promptBoxBtn.click();
        // Switch control to 'Prompt Box' popup
        Alert promptPopUp = driver.switchTo().alert();
        // Display the prompt message to console
        System.out.println(promptPopUp.getText());
        // Click 'OK'
        promptPopUp.accept();    
        
    } //End of @Test

    @After
    public void tearDown() throws Exception {
        // Close the Firefox browser
        driver.close();
    }
}

Explanation of the code:

  1. In order to instantiate a popup box, we will have to import “import openqa.selenium.Alert package”.

Once we type the above code, a squiggly line appears below the word, ‘Alert’. Upon hovering, eclipse will suggest all possible quick fixes. Click on the first fix that suggests importing ‘Alert’ package.

Import alert package

// Switch the control to 'Alert Box' popup
Alert alertPopUp = driver.switchTo().alert();

This package specifies the Alert interface which is used to used to handle web based pop-up box.

Here ‘alertPopUp’ is the new instance variable created to reference the displayed pop-up.

2. To switch the control from the main window to the popup window,

driver.switchTo().alert();

3. To get the text displayed in the popup box, getText() method is used on the instance variable that references to the generated alert.

// Print the alert message to console
System.out.println("Alert Box message: " + alertPopUp.getText());

4. To accept the alert, accept() method is used.

// Accept the alert popup
alertPopUp.accept();

5. To dismiss the alert, dismiss() method is used.

// Dismiss the popup
confirmPopUp.dismiss();

Execution Result:

In JUnit window, green bar shows that the test case is executed successfully. Console window shows the absence of any errors. It also shows all the printed messages as expected.

Alert Eclipse output

Time to practice and I will see you soon in another post. Have a great day!

 

 

4 Comments

  1. Hi,
    After clicking on Ok button on Alert pop up window, the main window get refreshed on your Demo website. That means whatever i have selecetd from Check Box, List before Pop up window is getting refreshed. Can you please help me to handle this.
    SV

  2. 3. void dismiss()
    This method is used to dismiss the alert. It clicks on the ‘Cancel’ button.

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

    The method is dismiss() but you have used accept() in the example.

    • Perfect! Thanks for highlighting that Gagan. Appreciate it. I have modified the code and executed an example to make sure it works 🙂
      I have used this dismiss() method in the sample scenario for dismissing the ‘Confirm Box’ pop up. Hope that helps.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.