Table of contents
1.
Introduction
2.
Alerts in Selenium
2.1.
Types of Alerts in Selenium
2.2.
Handling Alerts In Selenium
3.
Example
4.
Popups in Selenium
4.1.
Handling Popups in Selenium
5.
FAQs
5.1.
1. What is the difference between an alert and a popup?
5.2.
2. What is Alert in Selenium, an interface or a class?
5.3.
3. How do the confirmation alert and prompt alert differ from each other?
5.4.
4. Can we take a screenshot of an Alert in Selenium?
6.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Handling Alerts and Popup in Selenium

Author Anjali
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In this article, we will be discussing a crucial concept related to Alerts and Pop-Ups and their different types which appear on web pages. We will discuss various methods of handling alerts and popups in Selenium WebDriver depending on the Alert or the Popup type.

Alerts in Selenium

Alerts in Selenium are small message boxes that appear on the screen to provide the user with some information or notification. It notifies the user with some kind of information or error or asks for permission to perform specific tasks, and it also provides warning messages.

Also see, Xpath in Selenium

Types of Alerts in Selenium

  1. Simple Alert: This alert is just an informational alert and has an OK button on them. Users can click on that OK button after reading the message shown on the alert box. A simple alert box looks like as below:


     
  2. Prompt Alert: In this type of alert, some input requirement is there from the user end in the text that needs to be entered in the alert box. A prompt alert box is displayed below, where the user can enter their username and press the OK button or Cancel button in the alert box without entering any information.


     
  3. Confirmation Alert: This type of alert gets some confirmation from the user in the form of accepting or dismissing the message box. Users can only read this message and provide the inputs by clicking the OK or Cancel button.

Handling Alerts In Selenium

Whenever we execute any automation scripts in Selenium WebDriver, the WebDriver always focuses on the main browser window and will only run all the commands on the main browser window. But, whenever an alert or popup appears, it opens up in a  new window. So, for handling these Alerts using Selenium WebDriver, the focus must be shifted to the child windows opened by the Alerts. 

In order to switch the control from the parent window to the Alert window, the Selenium WebDriver provides the following command:

driver.switchTo( ).alert( );
You can also try this code with Online Java Compiler
Run Code


Once the control is switched from the main browser window to the alert window,  we can use the methods provided by the Alert Interface to perform various required actions like dismissing the alert, accepting the alert, getting the text from the alert window, writing some text on the alert window, etc.

To handle Javascript alerts, Selenium WebDriver provides package org.openqa.selenium.Alert and reveals the following methods:

1. Void accept(): This method clicks on the 'OK' button of the alert box.

driver.switchTo( ).alert( ).accept();
You can also try this code with Online Java Compiler
Run Code

 

2. Void dismiss(): We use this method when the 'Cancel' button clicks in the alert box.

driver.switchTo( ).alert( ).dismiss();
You can also try this code with Online Java Compiler
Run Code


3. String getText(): This method captures the message from the alert box.

driver.switchTo().alert().getText();
You can also try this code with Online Java Compiler
Run Code


4. Void sendKeys(String stringToSend): This method sends data to the alert box.

driver.switchTo().alert().sendKeys("Text");
You can also try this code with Online Java Compiler
Run Code

Example

Let us take an example in which we will automate the following procedures:
1. Invoke Firefox Browser
2. Open URL the URL of the web page to generate and confirm the Alert box.).
3. Generate the Alert box for testing.
4. Now, Click on the “Generate Confirm Box” button.
5. Close the browser.

We will create the test case step by step in order to have a better understanding of how to handle Alerts in Selenium WebDriver.

Step 1. Launch Eclipse IDE and create an open test suite "Demo_Test".

Step 2. Right-click on the "src" folder and then create a new Class File from New > Class.


Give the Class name as "alert_test" and then click on the "Finish" button.


Step 3.  Now coming to the coding ground.

1. To invoke the Firefox browser, we need to download the Gecko driver and set the system property of "Running test on Firefox Browser" as the path of the geckodriver.exe file. Here is the sample code snippet to set the system property for the Firefox driver:

// System Property for Gecko Driver   
System.setProperty("webdriver.gecko.driver","Location to the geckodriver.exe");  
You can also try this code with Online Java Compiler
Run Code

 

2. After that, we have to initialize the Gecko Driver using the Desired Capabilities Class.
Here is the sample code snippet to initialize the Gecko driver using DesiredCapabilities class.

// Initialize Gecko Driver using Desired Capabilities Class  
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette",true);  
WebDriver driver= new FirefoxDriver(capabilities) 
You can also try this code with Online Java Compiler
Run Code


By combining both of the above code blocks, we will get the below code to launch the Firefox browser.

// System Property for the Gecko Driver   
System.setProperty("webdriver.gecko.driver","Location to the geckodriver.exe");

// Initialise Gecko Driver using Desired Capabilities Class  
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette",true);  
WebDriver driver= new FirefoxDriver(capabilities) 
You can also try this code with Online Java Compiler
Run Code


3. Now, we need to write the code which will automate our second test procedure(navigate to the chosen URL). Here is a sample code to navigate to the chosen URL:

// Launch the Website  
driver.navigate().to("URL of the web page to generate and confirm the Alert box.");  
You can also try this code with Online Java Compiler
Run Code


The complete code till now will look like below:

import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.firefox.FirefoxDriver; 
import org.openqa.selenium.remote.DesiredCapabilities;  

public class alert_test{ 
	public static void main(String[] args){            

    	// System Property for the Gecko Driver
		System.setProperty("webdriver.geckodriver.driver","Location to the geckodriver.exe");  

		// Initializing Gecko Driver using Desired Capabilities Class.      
		DesiredCapabilities capabilities = DesiredCapabilities.firefox();
		capabilities.setCapability("marionette",true);    
    	WebDriver driver=new FirefoxDriver();  

    	// Launch the Website
    	driver.navigate().to("URL of the web page to generate and confirm the Alert box");    
   	}  
}  
You can also try this code with Online Java Compiler
Run Code


Step 4. Now we will locate the “Generate Alet Box” and “Generate Confirm Box” to perform alert handling operations. This is done by inspecting its HTML codes by following the below steps :

1. Open URL: URL of the web page to generate and confirm the Alert box.
2. Right-click on the “Generate Alert Box” button on the sample web page and select Inspect Element
3. It will launch a window containing all the specific codes involved in developing the “Generate Alert Box” button.
4. Take note of its link text that is “Generate Alert Box”.
5. Similarly, we will inspect the “Generate Confirm Box” button.
6. Take note of its link text “Generate Confirm Box”.

Step 5. To automate our third test procedure, we need to write the code which clicks and accepts the Generate Alert Box and accepts the Generate Confirm Box.
Here is the sample code for handling alert boxes.

//Handling the alert box 
//Click on the “Generate Alert Box” button  
driver.findElement(By.linkText("Generate Alert Box")).click(); 

//Using Alert class to first switch the focus to the alert box  
Alert alert = driver.switchTo().alert();  

//the accept() method is used to accept the alert box  
alert.accept();  

//Handling the confirm box  
//Click on the “Generate Confirm Box” button  
driver.findElement(By.linkText("Generate Confirm Box")).click(); 

Alert confirmBox = driver.switchTo().alert();  
     
//dismiss() command is used to dismiss the confirm box  
confirmBox.dismiss(); 

//Similarly, accept() can be used to accept the confirm box 
You can also try this code with Online Java Compiler
Run Code


Hence, our final test script will look like this:  

import org.openqa.selenium.By;  
import org.openqa.selenium.WebDriver;  
import org.openqa.selenium.WebElement;  
import org.openqa.selenium.firefox.FirefoxDriver;  
import org.openqa.selenium.Alert;  
import org.openqa.selenium.remote.DesiredCapabilities; 

public class alert_test{ 

	public static void main(String[] args){            

    	// System Property for the Gecko Driver
		System.setProperty("webdriver.geckodriver.driver","Location to the geckodriver.exe");  

  		// Initializing Gecko Driver using Desired Capabilities Class.      
		DesiredCapabilities capabilities = DesiredCapabilities.firefox();
		capabilities.setCapability("marionette",true);    
  		WebDriver driver=new FirefoxDriver();  

   		// Launch the Website
  		driver.navigate().to("URL of the web page to generate and confirm the Alert box.");

		//Handling the alert box 
		//Click on the “Generate Alert Box” button  
		driver.findElement(By.linkText("Generate Alert Box")).click();  

		//Using Alert class to first switch the focus to the alert box  
		Alert alert = driver.switchTo().alert();  

		//the accept() method is used to accept the alert box  
		alert.accept();  

		//Handling the confirm box  
		//Click on the “Generate Confirm Box” button  
		driver.findElement(By.linkText("Generate Confirm Box")).click(); 

		Alert confirmBox = (Alert) driver.switchTo().alert();  
     		
		//dismiss() command is used to dismiss the confirm box  
		((Alert) confirmBox).dismiss(); 
		//Similarly, accept() can be used to accept the confirm box 
      	
   	}  
} 
You can also try this code with Online Java Compiler
Run Code


The following picture shows the Eclipse window for the test script.

Step6. Right click on the Eclipse code and select Run As > Java Application.



After execution, the above test script will launch the Firefox browser and automate all the test procedures.

Popups in Selenium

During automation, whenever we have multiple windows in any web application, the activity needs to switch the control among several windows from one to another in order to complete the operation. After completion of the process, it needs to return to the main window, which is the parent window in Selenium. 

Handling Popups in Selenium

In Selenium web driver, there are methods with the help of which we can handle multiple windows.

  1. Driver.getWindowHandles(): To handle all opened windows by web driver, we can use “Driver.getWindowHandles()” and then we can switch window from one window to another in a web application. Its return type is Iterator<String>.

     
  2. Driver.getWindowHandle(): When the site opens, we need to handle the main window by driver.getWindowHandle(). This will handle the current window that uniquely identifies it within this driver instance. Its return type is String.

FAQs

1. What is the difference between an alert and a popup?

Ans: An Alert is basically used to display a warning message. In comparison, a popup is a window that comes up on the screen.
 

2. What is Alert in Selenium, an interface or a class?

Ans: An Alert is an interface that is implemented by an inner class “RemoteAlert”.
 

3. How do the confirmation alert and prompt alert differ from each other?

Ans: Confirmation alerts are different from prompt alerts in a way that the user cannot enter anything as there is no text box available in them, while in prompt alert boxes, users can enter details.
 

4. Can we take a screenshot of an Alert in Selenium?

Ans: We cannot take screenshots of an unhandled Alert in Selenium. If we want screenshots for debugging, we can use Robot to capture screenshots. 

Key Takeaways

In this blog, we talked about Alerts and their types like simple alerts, prompt alerts, and confirmation alerts. We also discussed the different ways to handle these alerts. Then we studied what popups are and the various ways to handle them in Selenium WebDriver.

We hope this blog helped you enhance your knowledge regarding Alerts and Popups in Selenium WebDriver. Learning never stops, and to learn more and become more skilled, head over to our practice platform Coding Ninjas Studio, practice top problems, attempt Mock Tests, and read informative blogs and interview experiences. Do upvote our blog to help other ninjas grow. 

Happy Learning!

Live masterclass