How to work with modals in Selenium


In this post, you will learn how to work with modals in Selenium WebDriver. There are two main types of modals. The first type is purely informative and does not require any user input. However, the second type of modal may require user input.

Table of contents

Introduction

A modal is a popup window that is displayed on top of the current page. There are different types of modals. Some can be very simple as in the following example.

How to handle a modal in Selenium that only contains a single button to close the modal.

As you can see, this modal only displays a message and a button that a user can click on to close the modal.

You may need to fill out a form in other modals.

How to handle a modal in Selenium that contains not only a button to close the modal but also an input form.

Notice that this modal not only contains a button to close the modal but that it also contains a form.

It is important to note that all modals require immediate attention. What this means is that a user must either interact with the modal or dismiss. Otherwise they won’t be able to return to the main web page.

Modal vs alert boxes or windows

The main difference between a modal and an alert box is that modals do not require the use of special methods to work with them. For example, before interacting with an alert box, a user must switch to it.

driver.switchTo().alert()

This is not necessary for modals as you will see next.

How to work with modals in Selenium

To enter text in a modal window you first locate the input element, then you simply enter the text. This code snippet shows you how to do this.

driver.findElement(locator).clear();
driver.findElement(locator).sendKeys(text);

The following video will show you how complete the form shown in the second modal shown earlier.

Conclusion

And now you know how simple it is to handle modals in Selenium. You learned that modals do not require the use of special WebDriver methods. When a user encounters a modal window, they must stop what they are doing and pay the modal immediate attention.

To practice this example for yourself, click here.

Leave a Reply