Handling Pop-Up Windows in Selenium
Tags: qa, programming, selenium, testing
Published: 2023-08-27 10:32:42

Welcome! Today we’re going to look into the pop-up windows handling using Selenium. If you like this article please feel free to follow me on [Telegram channel](https://t.me/ta_stories), there are many more thought related to development, processes and test automation.

## Introduction
Sooner or later in the life of any testing automation specialist (regardless of the programming language you work with), a situation arises where it becomes necessary to handle pop-up windows in the browser. One might think that in the era of reactive applications, phenomena like pop-up windows should have taken a back seat, as modern tools offer a rich variety of implementing modal windows through HTML code on the page rather than relying on the browser’s features. However, it’s important not to forget that our world is not perfect, and not all projects are built using React/Vue/Angular. Therefore, it’s reasonable to expect that dealing with browser pop-up windows is still something we might encounter.

### What Are Pop-Up Windows?
Pop-up windows are a browser feature that has come to us from the distant years when web development wasn’t yet mainstream. However, pop-up windows still exist even in modern versions of JavaScript. Developers have taken care of backward compatibility to avoid breaking projects that were written long ago.

Pop-up windows serve two main purposes:

- User Interaction: When we need to convey important information to the user or request certain data without which further progress is impossible, a pop-up window comes to the rescue.

- Preventing User Interaction: They prevent users from interacting with the web page’s interface until the user responds to a message by clicking a button.

## Types of Pop-Up Messages

### Simple Alert
This message contains a single button — OK. By clicking on it, we simply close the pop-up window and can continue working with the web interface. Let’s see what it looks like.

Open the developer console in your browser (F12) and navigate to the Console tab:

![Developer's console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kxj1syplaa5o8v9v3uos.png)

We have the JavaScript command line before us, where we can write code that the browser will execute. Enter the command alert('This is alert'); in the interpreter and press Enter. As a result of execution, we see a pop-up window with the message 'This is alert':

![Alert pop-up](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fc0y7gpsct0r7mt9qazg.png)

Such a window can be used to display important information to the user for their awareness, without giving them the option to make any choice.

### Confirmation Window
This window presents a message with two possible actions — OK and Cancel. The behavior of such a window is more complex than that of a simple alert. Different code fragments will be executed based on the option chosen by the user. The purpose of this article is to learn how to handle such pop-up windows using Selenium tools, so we won’t delve into the detailed implementation of different user choices.

To invoke a confirmation window, we need to perform the same steps as we did to bring up an alert, but use a different command: confirm('Choose your destiny:');. As a result of executing this code, the following window will be displayed:

![Confirm pop-up](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/znaksoifc2j1v7uzkv48.png)

### Input window
And finally, the last type of pop-up window is an input window, where the user can not only choose from two available options but also write their own response. This type of window can also be triggered from JavaScript by executing the following command: prompt('What is your favorite test automation library?', 'Selenium');. The prompt command takes two arguments - the message that will be displayed to the user and the default response (in our case, Selenium). As a result of executing this code, the following window will be shown with the suggested response (though we can, of course, enter our own response or even decline to provide any data by clicking the Cancel button):

![Prompt pop-up](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w6m8gj972dibnwb50co6.png)

## Why Handling Pop-Up Windows in Selenium is Necessary
To answer this question, let’s perform a small exercise for all three types of pop-up windows:

- While on any webpage in your browser, open the developer console and trigger a pop-up window.
- As soon as the window appears on the screen, try interacting with the elements on the page (images, links, etc.).
- Close the pop-up windows using various methods (by clicking available buttons or by providing information in the prompt window). Take note of what is displayed in the developer console when closing the windows in different ways.

If you’ve done everything correctly, the answer to why handling pop-up windows in test automation is necessary becomes quite clear:

1. A pop-up window prevents the user from interacting with the elements on the page. Consequently, while the window is open, a Selenium automated test cannot proceed further.
2. By clicking different buttons and entering information (only for prompt-type windows), we obtain different values. This means we can emulate various user scenarios. Thus, we can create a set of automated tests that cover all possible user interaction scenarios.

## Interacting with Pop-Up Windows in Selenium
Now that we understand where pop-up windows come from and why they are important, let’s practice and learn how to work with them in Selenium. We already have a web page that is perfect for this purpose: https://testpages.herokuapp.com/styled/alerts/alert-test.html

### Switching to a Pop-Up Window
Let’s write a simple test that clicks a button and triggers the appearance of a pop-up window. All examples are written in the Java programming language using the selenium-java library. However, the code can be easily adapted to other programming languages since the Selenium library interface is similar across all languages. In the code example below, the WebDriver initialization is omitted, as we are focusing on working with windows:
```
// Clicking on the button that causes alert message
driver.findElement(By.id("alertexamples")).click();

// Switching WebDriver context to the pop-up window
driver.switchTo().alert();
```

### Retrieving Text from a Pop-Up Window
In the example above, in the last line, we switched Selenium’s focus to the alert (this will also work for confirm or prompt windows). Calling the alert() method returns a special class called Alert, which helps us work with pop-up windows.

Now we can write a complete test that verifies the text of the alert against the expected text. To do this, we will use the getText() method in the Alert class:

```
@Test
void testAlert() {
    driver.findElement(By.id("alertexamples")).click();

    // Get pop-up window text message
    String message = driver.switchTo().alert().getText();

    assertEquals("I am an alert box!", message);
}
```

### Closing a Pop-Up Window
Our example is quite simple. In practice, it’s often not enough to just retrieve text from a window, you might need to close pop-up windows to continue working. To achieve this, you need to learn how to close pop-up windows using Selenium.

For practice, let’s try the second type of pop-up window — confirm. On our test page, the user’s choice is displayed in a separate message that appears below the button. We will use this to test various methods of interacting with pop-up windows.

The Alert class has two methods:

- `accept()`: This method makes Selenium click the "OK" button of the pop-up window of any type.
- `dismiss()`: Similar effect, but it will click the "Cancel" button of the pop-up window.

```
@Test
void testAcceptConfirm() {
    driver.findElement(By.id("confirmexample")).click();

    // Accept the confirm (OK)
    driver.switchTo().alert().accept();

    boolean result = Boolean.parseBoolean(driver.findElement(By.id("confirmreturn")).getText());
    String clickedButton = driver.findElement(By.id("confirmexplanation")).getText();

    assertTrue(result);
    assertTrue(clickedButton.contains("You clicked OK"));
}

@Test
void testDismissConfirm() {
    driver.findElement(By.id("confirmexample")).click();

    // Dismiss the confirm (Cancel)
    driver.switchTo().alert().dismiss();

    boolean result = Boolean.parseBoolean(driver.findElement(By.id("confirmreturn")).getText());
    String clickedButton = driver.findElement(By.id("confirmexplanation")).getText();

    assertFalse(result);
    assertTrue(clickedButton.contains("You clicked Cancel"));
}

```

### Entering User Input
We’ve come a long way, but there’s one last scenario to cover: entering our own message into a pop-up window. Let’s see how we can achieve this, especially considering that the last button on our web page remains untested.

So, here are our two test scenarios:

1. Click the button, enter a message, and click “OK.”
2. Click the button, enter a message, and click “Cancel.”

To implement these scenarios, you need to familiarize yourself with a new method of the Alert class:

`sendKeys()` - used to enter text into a prompt-type window. Let's look at the tests that utilize this method:

```
@Test
void testAcceptPrompt() {
    driver.findElement(By.id("promptexample")).click();
    String text = "I like test automation!";

    // Enter text and press ОК
    driver.switchTo().alert().sendKeys(text);
    driver.switchTo().alert().accept();

    String message = driver.findElement(By.id("promptreturn")).getText();
    String clickedButton = driver.findElement(By.id("promptexplanation")).getText();

    assertEquals(message, text);
    assertTrue(clickedButton.contains("You clicked OK"));
}

@Test
void testDismissPrompt() {
    driver.findElement(By.id("promptexample")).click();
    String text = "I like test automation!";

    // Enter text and press Cancel
    driver.switchTo().alert().sendKeys(text);
    driver.switchTo().alert().dismiss();

    String message = driver.findElement(By.id("promptreturn")).getText();
    String clickedButton = driver.findElement(By.id("promptexplanation")).getText();

    assertEquals(message, "");
    assertTrue(clickedButton.contains("You clicked Cancel"));
}
```

## Conclusion
In this article, we covered working with pop-up windows in Selenium:

- We learned that different types of pop-up windows exist: alert, confirm, prompt.
- We learned how to trigger the appearance of pop-up windows using JavaScript commands.
- We discovered that Selenium has a special class, Alert, for working with pop-up windows.
- Using the getText() method, we learned how to retrieve the message within a pop-up window.
- With the accept() and dismiss() methods of the Alert class, we learned how to click "OK" and "Cancel" buttons in pop-up windows, thus deciding the user's path.
- Using the sendKeys() method, we learned how to input our own message into prompt-type windows.

As seen from the code, working with pop-up windows isn’t as complex as it might seem. The “magic” has already been written by the developers of the Selenium library, and we simply need to utilize the provided methods. Keep these code examples, use them in your daily work, and, of course, don’t stop to automate!