Skip to main content

How to Work with JavaScript Alerts

Intro​

Built into Selenium is the ability to switch to an alert window and either accept or dismiss it. This way your tests can continue unencumbered by dialog boxes.

A popular use case for alerts is in the case of error prevention for password restrictions.

If your application triggers any JavaScript pop-ups (a.k.a. alerts, dialogs, etc.) then you need to know how to handle them in your Selenium tests.

A Solution​

Built into Selenium is the ability to switch to an alert window and either accept or dismiss it. This way your tests can continue unencumbered by dialog boxes that may feel just out of reach.

Example​

Our example application is available here on the-internet. It has various JavaScript Alerts available (e.g., an alert, a confirmation, and a prompt). We'll work with the JavaScript Confirmation, since it has more than one option to choose from (Ok and Cancel).

A quick glance at the page's markup shows that there are no unique IDs on the buttons. So to click on the second button (to trigger the JavaScript confirmation dialog) we find all buttons on the page and click the second one.

After clicking the button we wait for the JavaScript pop-up to appear and switch to it. Then we accept it (to click Ok) in the first test, and dismiss it (to click Cancel) in the second one. Once the alert is gone, our main browser window automatically regains focus and the page displays the result that we chose. This text is what we use for our assertion, making sure that the right option was chosen.

Expected Behavior​

  • Open the browser
  • Load the page
  • Click the second button on the page
  • JavaScript Confirmation Alert appears
  • Accept (or dismiss) the JavaScript Confirmation Alert
  • Assert that the result on the page is what we expect
  • Close the browser

Summary​

We've learned how to accept or dismiss JavaScript alerts with Selenium. After accepting or dismissing the alert, the main browser window regains focus, and we can continue with our test.

Happy Testing!

Special Thanks​

Roman Isko
Contributed the initial Java code for this tip.

Authors​

Dave Piacente
Original creator of Elemental Selenium
Diego Molina
Elemental Selenium maintainer