How to Handle Alert and Pop-ups in Selenium WebDriver

How to Handle Alert and Pop-ups in Selenium WebDriver?

Last updated on 19th Sep 2020, Artciles, Blog

About author

Siva (Sr Technical Project Manager )

He is a TOP-Rated Domain Expert with 6+ Years Of Experience, Also He is a Respective Technical Recruiter for Past 3 Years & Share's this Informative Articles For Freshers

(5.0) | 16677 Ratings 559

When we are testing an application, we test that application with some set of predefined rules, and when it does not expect as per the predefined rules, it will send an error or an alert is displayed. So dealing with those alerts is a challenging task, but in this article, I will try to share how you can handle these alerts.

What is an Alert?

Alerts are nothing but small message boxes that are displayed on the screen to give some information or ask permission to perform some operation. Sometimes its also used for warning purposes.

Types of Alerts in Selenium

Mainly we are dealing with two types of alerts that are:

  • Windows-based alert pop-ups
  • Web-based alert pop-ups

As we know that by using the Selenium WebDriver it is not possible to test window based applications, that’s why we are using some third-party tools to handle the window-based pop-ups.

There are mainly 3 types of alerts are there that are:

  • Simple alert
  • Prompt alert
  • Confirmation alert
Subscribe For Free Demo

Error: Contact form not found.

Simple alert:

The simple alert has only an Ok button. These types of the alert are mainly used to display some information to the user.

Prompt alert:

In this type of alert, you will get a text box with an Ok and cancel button. These types of the alert are mainly used when you need some more information at the time of running your automation script. To enter the information in the alert box, you can use the sendKeys() method.

Confirmation alert:

This type of os alerts are coming with an option to accept or dismiss. To accept the alert, you can use the alert.accept(), and to dismiss, you can use the method alert.dismiss().

I hope you have an overall idea about the different types of alerts. Now you can easily understand how you can handle different types of alert easily.

How to handle Alerts in Selenium WebDriver?

Handling alerts is one of the tricky tasks, but Selenium WebDriver provides some of the predefined methods, which makes the handling process so easy.

When we are executing our automation script, we are creating an object of browser class, and that driver object has control over all the browser operations even on alert too. For handling the alert, you can use the alert interface methods to perform required operations.

Alert Methods:

  • Void dismiss(): When you call this method it will click on the cancel button. driver.switchTo().alert().dismiss();
  • Void accept(): When you call this method it will click on the Ok button. driver.switchTo().alert().accept();
  • String getText(): By using this method you can get the alert message. driver.switchTo().alert().getText();
  • Void sendKeys(String stringToSend): This method will help you to send data to the alert box. driver.switchTo().alert().sendKeys(“Text”);

Why Do You Need to Test Alerts And Popups in Selenium Protractor?

Alerts and pop-up in Selenium Protractor are widely used to issue warnings to the user or asking permission from them. They allow us to take the user’s permission for certain actions on the web page. 

Let’s take a scenario to make things simple. You want to log in to a website, but if you enter the wrong email or password to the required fields, you’ll get an alert stating the wrong email or password. Alerts and popups help in establishing user flow in web application and notify them in case something goes wrong, this is you should be handling alerts and popups in Selenium

There can be several instances that cause an alert to popup in protractors when browsing web pages. However, the most commonly observed classification of alerts is observed during execution of actions such as:

  • To show a message or important alert to the user.
  • To notify the user about an update.
  • To show error and notify the user in case of  incorrect data entry.
  • To show a message on saving certain information.

Handling Alerts in Selenium Protractor

The purpose of alerts on a webpage is to drive the attention of the user. If an alert is present on a webpage the user may have to input operation in order to address such alerts. 

The formation of Alerts on a web page is done utilizing the JavaScript framework. The characteristics of alerts often block the source page and force the intended user to read the alert before they can access the web page. 

  • The Alerts in the protractor framework are not part of a window therefore they cannot be handled by utilization of JavaScript Executor. 
  • In Alerts one cannot write Xpaths and the same cannot be identified through inspecting tools. 
  • The characteristic of Alerts block the operation webpage and does not allow the performance of any task on the web page unless the alert is handled on a priority basis. 
  • If a user attempts to proceed on the webpage without prior handling of the Alert popup then they may receive “Unhandled Alert Error”.

Alerts can be classified into the following types:

  • Prompt
  • Alerts
  • Confirmation Dialogue

These alerts are further explained in detail in this Selenium Protractor tutorial below:

Prompt

The prompt alert is utilized to derive value from the user in a text format. It contains a text bar in which the user can input their values. This alert type is not commonly used in webpage alerts. 

The-prompt-alert-is-utilized-to-derive

Alert

This type of alert() method ideally displays a message box with an “OK” button integrated with the dialogue box. This method is utilized with the intent to inform the target user of any specific operational details or changes therewith. Examples of alerts can be: Successfully Loaded webpage or any other database information alerts. 

Course Curriculum

Best Selenium WebDriver Certification Course to Boost UP Your Skills

  • Instructor-led Sessions
  • Real-life Case Studies
  • Assignments
Explore Curriculum

The presence of the alert command is solely to inform the user of existing information. The command can be created by utilizing alert(“message”) in JavaScript. The Alert Pop-up can be handled clicking on the “X” or “OK” command.  

command-can-be-created-by-utilizing-alert

Confirmation Dialogue

The confirmation alert is based on the incidence of the dialogue box information being true or false. This alert type is embedded with two commands “OK” or “Cancel”. This is a choice based command box in which the user determines the correctness of the information by clicking on “OK” or “Cancel”. 

confirmation-dialogue-alert

Handling Alerts in Selenium Protractor Using Alert Class 

In Alert Class, the user is presented with four methods in handling alerts in Selenium Protractor. The user may dismiss, accept, retrieve details or send key values with intent to handle the alerts on a web page. 

Alert Class Methods:

  • dismiss()
  • accept()
  • sendKeys()
  • getText()

First, we have to create the object in the Alert Class for handling alerts in Selenium. The same can be executed by entering the command:

JavaScript

    1. Alert alert = new Alert() ;

Once the object command is executed we need to direct the command to the webpage in which the operation is required to be performed for handling alerts and popups in Selenium. This is because the object command merely contains the memory address.

Next, we will direct the browser object to the Alert class, so that it identifies the browser (Chrome, Firefox) on which it has to create its operation.  

JavaScript

    1. var abc :Alert=browser.switchTo().alert();
    2. // dynamic javascript to switch to alert
    3. var abc=browser.switchTo().alert();

dismiss() Alert Class Methods in Selenium Protractor

The dismiss() alert class method is used to close the alert for handling alerts in Selenium. It operates by clicking on the “X” button in the prompt. This method is functional for all alert types: prompt, alert and confirmation dialogue box.  The protractor web driver uses a void dismiss() command to cancel the alert. 

JavaScript

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

accept() Alert Class Methods in Selenium Protractor

The accept() alert class method is used to accept an alert and continue with the webpage operation. The accept alert can be utilized for all JavaScript alert types.

An alert command can be executed by using the ale variable for handling alerts in Selenium:

  • 1 var myAlert = browser.switchTo().alert();
  • 2 // clicking the ‘OK’ button will confirm the action
  • 3 //myAlert.accept();

sendKeys() Alert Class Methods in Selenium Protractor

The sendKeys() command can help the user to set certain values to the prompt. The nature of the sendKeys() command is to input value based responses. It can handle all the JavaScript based alerts.

The following command is executed to launch handle sendKeys() Alert Class Methods in Protractor:

Course Curriculum

Get Selenium Webdriver Training from Industry Experts Trainers

Weekday / Weekend BatchesSee Batch Details
  • // import the required modules from the library for handling alerts and popups in Selenium//
  • import { browser, element, by, ExpectedConditions} from ‘protractor’import { Alert } from ‘selenium-webdriver’;
  • var script = require (‘protractor’) ;
  • var webdriver = require (‘selenium-webdriver’) ;
  • var myAlert = new Alert();

Handling Popups in Selenium Protractor

Popups are windows that pop up on your screen when you perform a certain action on the web application. These can be when you download a file, or when you enter a password protected website, there are several such cases and i’ll share them with you in the next section of this Selenium Protractor tutorial.

While performing Selenium test automation on a web page, a tester may needs to be handling popups in Selenium of different types, these are:

  • Download popups
  • Authentication popups
  • Confirmation popups
  • Alert popups
  • Hidden Division popups
  • Upload popups
  • Calendar popups

Next, I’ll go into handling popups in Selenium, here are some of the pop-ups you should know how to handle:

Hidden Division Popups

Hidden division popup is the newer version of protractor alert that has gained preference with new developers. This alert is an HTML code that stays hidden at the beginning of the loading of a webpage. The execution of the hidden division pop-up is activated by clicking on a pre-set trigger tab. popups such as contact forms; error messages are the most common form of hidden division popups.

A hidden division popup can be identified by the following characteristics:

  • It is not a form of JavaScript pop-up
  • It can integrate another division of pop-up with the initial alert dialogue.
  • It can be customized to contain a scroll bar for extended content.
  • Hidden division popups are customizable and resizable
  • These popups are locked in a single space and cannot be moved by the user.
  • These popups can be inspected
  • These popups do not allow the user to operate further until the alert is handled.
  • Non-handling the popup triggers selenium to throws ElementNotClickableError

The complete command for hidden division popups that is executed for handling popups in Selenium :

  • // import the required modules from the library or handling popups in Selenium //
  • import { browser, element, by, ExpectedConditions, protractor} from ‘protractor’
  • import { Alert } from ‘selenium-webdriver’;
  • var script = require (‘protractor’) ;
  • var webdriver = require (‘selenium-webdriver’) ;
  • var myAlert = new Alert();

Authentication Popups

The key usage of authentication popups is to authenticate user access. These popups are generally observed in password-protected pages and consist of a username and password dialogue boxes.

An authentication popup can be identified by the following characteristics:

  • The elements of the authentication pop-up overlay cannot be inspected by the user.
  • This pop-up is displayed on the occurrence of the loading of the web-page.
  • The page can only be accessed through the input of valid credentials.
  • The pop-up may or may not be movable as per the browser configuration.
  • The UI of the pop-up is highly customizable.

The solution to handle this type of alert in selenium is to enter valid credentials along with the URL. The syntax for password and username in authentication pop-ups are:

  • 1.driver.get(protocol://Usename:Password@URL Address);

The complete command for Authentication popups for handling popups in Selenium is:

  • // import the required modules from the library for handling popups in Selenium //
  • import { browser, element, by, ExpectedConditions, protractor} from ‘protractor’
  • import { Alert } from ‘selenium-webdriver’;
  • var script = require (‘protractor’) ;
  • var webdriver = require (‘selenium-webdriver’) ;
  • var myAlert = new Alert();

Upload Popups

The upload pop-up is an alert type that is triggered when the user needs to upload a certain file to the web-page. This pop-up is customized to initially ask permission for local storage access to browse files that need to be uploaded. The upload command box consists of the “browse/choose” tab. clicking on the tab triggers a system based operation in which the local storage of the user is opened.

Once the trigger command opens the local storage the user needs to select the file that needs to be uploaded and click on the “ok” confirmation button. This action will successfully upload the target file to the webpage. The user will further need to click on the “upload file” button in order to send the file to the storage database of the webpage.

To execute this command the sendkeys() method can be efficiently utilized. The detailed code to execute the sendkey() command for handling popups in Selenium for dialogue box is:

  • // import the requiredmodules from the library for handling alerts and popups in Selenium //
  • //import { browser, element, by, ExpectedConditions, protractor} from ‘protractor’
  • import { Alert } from ‘selenium-webdriver’;
  • var script = require (‘protractor’) ;
  • var webdriver = require (‘selenium-webdriver’) ;
  • var myAlert = new Alert ();

Integrating With Cloud Selenium Grid And Other Tools

We constantly look for ways to help us increase our test coverage and enhance our test case while running our Selenium test automation scripts. To support this, there are several tools to scale our testing efforts. The Protractor is capable of integrating with many other popular tools and platforms such as Github, Jenkins, Selenium Grid etc. It’s best that we utilize this capability of Protractor to scale your testing efforts.

selenium Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

By providing substantial added value, these tools make our Protractor test script more efficient and reliable. Whether a novice or a professional with Protractor, one of the best tools to get started is to deploy the application on Online Selenium Grid like LambdaTest and quickly monitor our testing very easily. Integrating LambdaTest in our Protractor scripts allows us to improve our test coverage and ensure that we’ve covered our browser matrix.

By utilizing a cloud Selenium Grid, you can run test scripts on 2000+ real browsers and their different versions, which helps us to adequately construct the test case and maximize our test coverage. You can further use a Selenium Grid for handling alerts and popups in Selenium over different browsers and OS combinations.

Integrating Protractor with a cloud Selenium Grid is easy, you just have to make changes to specification files as only a config file is required, which will have all the connection information, the hub, and the access key needed to connect to the LambdaTest network. Therefore, when combined with the internal capabilities of Protractor, it gives greater flexibility to handle our tests and run parallel tests, which will exponentially improve our test run speed. 

Conclusion

Now, this takes us to the conclusion of this Selenium Protractor tutorial on handling alerts and popups in Selenium protractor. There are several options for notifying users with critical information about the web application flow and it should be kept in mind while writing scripts for automated browser testing. I explored how browsers have native alert dialogs that can be used to give prompts using JavaScript and also create our own custom alerts and popups. But you need to keep in mind that the ability to show messages to the user is not overused as this may annoy the user and ruin their experience. 

Are you looking training with Right Jobs?

Contact Us

Popular Courses