Handle Alert, Popup and Dialogs Using Playwright Java

When automating web applications with Playwright in Java, one common challenge testers face is dealing with alerts, popups, and dialog boxes. These are browser-level interruptions that require user action, such as clicking OK, choosing Cancel, or entering text before proceeding further. If these are not handled properly, your automation scripts can get stuck and fail.

In this article, we’ll explore in detail how to handle alerts, confirm dialogs and prompts in Playwright Java. We’ll break down the logic behind dialog handling, cover multiple scenarios, and explain best practices so you’ll never get stuck when your application throws an unexpected popup.

Throughout this article, we will use the alerts and dialogs present on our playground website – https://testkru.com/Interactions/Alerts.

Alerts and Dia

Before jumping into the implementation, let’s clarify what these terms mean in the context of web automation:

  • Alert – A simple popup with a message and an OK button. Example: alert(“Action successful!”).
  • Confirm Dialog – A popup with two options: OK and Cancel. Example: confirm(“Are you sure you want to delete?”).
  • Prompt Dialog – A popup asking for input from the user. Example: prompt(“Enter your name:”).

Playwright offers a Dialog interface to handle alerts, confirmation boxes, and prompt dialogs.

Whenever a page triggers an alert, confirm, prompt, or dialog, Playwright emits a Dialog event on the page. To manage this, we need to:

  • first subscribe to the dialog event, and
  • then perform the action that triggers the alert or dialog to appear.

The golden rule: Attach the handler before the action that opens the dialog.

A JavaScript alert contains only a message and an OK button.

Let’s see how to handle this scenario in Playwright. On the page https://testkru.com/Interactions/Alerts, there’s a highlighted element in the image below. When you click it, a JavaScript alert will appear.”

Javascript alert
javascript alert

So, how do we go about accepting the alert? Let’s take it step by step.

First let’s write the code to subscribe to the dialog event –

page.onDialog(dialog -> {
         
});

Inside the dialog handler, you can perform different operations based on your needs. For example, you can fetch the text displayed in the alert using dialog.message(), or you can simply accept the alert by calling dialog.accept().

// Listen for any alert/confirm/prompt dialogs and accept them
page.onDialog(dialog -> {
        System.out.println("Message: " + dialog.message());
        dialog.accept(); // Accepts the dialog (clicks "OK")
});

Next, we need to locate the element and click on it to trigger the alert. In this example, the element can be identified using the XPath: //button[@class=’btn btn-warning’].

// Locate the alert trigger button using XPath
Locator alertButton = page.locator("//button[@class='btn btn-warning']");

// Click the button to trigger the alert
alertButton.click();
import com.microsoft.playwright.*;

public class CodekruTest {

    public static void main(String[] args) {

        // Start Playwright engine
        Playwright playwright = Playwright.create();

        // Launch Chromium browser in non-headless (visible) mode
        Browser browser = playwright.chromium().launch(
                new BrowserType.LaunchOptions().setHeadless(false)
        );

        // Create a new isolated browser context (like a fresh profile)
        BrowserContext context = browser.newContext();

        // Open a new tab (page) inside the context
        Page page = context.newPage();

        // Navigate to the Alerts test page
        page.navigate("https://testkru.com/Interactions/Alerts");

        // Listen for any alert/confirm/prompt dialogs and accept them
        page.onDialog(dialog -> {
            System.out.println("Message: " + dialog.message());
            dialog.accept(); // Accepts the dialog (clicks "OK")
        });

        // Locate the alert trigger button using XPath
        Locator alertButton = page.locator("//button[@class='btn btn-warning']");

        // Click the button to trigger the alert
        alertButton.click();

        // Close the browser instance
        browser.close();

        // Close Playwright engine
        playwright.close();
    }
}

Output –

Message: This is a simple alert!

This confirms that we successfully retrieved the alert message and accepted the alert.

A confirmation popup usually asks the user to accept or cancel an action.

Let’s take the example of the below-highlighted element, when clicked, will trigger a confirmation popup

confirmation popup button
confirmation popup

Here, we will do below things

  • Get the message written inside the popup.
  • and then dismiss/cancel the popup.

Most of the code will remain the same as we used for handling javascript alerts. The only difference is that:

  • instead of accepting the alert, we’ll dismiss it using dialog.dismiss().
  • Since we are working with a different element, we also need to update the XPath to //button[@class=’btn btn-info’].
        // Listen for any alert/confirm/prompt dialogs and accept them
        page.onDialog(dialog -> {
            System.out.println("Message: " + dialog.message());
            dialog.dismiss(); // Dismisses the dialog (clicks "Cancel")
        });

        // Locate the alert trigger button using XPath
        Locator alertButton = page.locator("//button[@class='btn btn-info']");
import com.microsoft.playwright.*;

public class CodekruTest {

    public static void main(String[] args) {

        // Start Playwright engine
        Playwright playwright = Playwright.create();

        // Launch Chromium browser in non-headless (visible) mode
        Browser browser = playwright.chromium().launch(
                new BrowserType.LaunchOptions().setHeadless(false)
        );

        // Create a new isolated browser context (like a fresh profile)
        BrowserContext context = browser.newContext();

        // Open a new tab (page) inside the context
        Page page = context.newPage();

        // Navigate to the Alerts test page
        page.navigate("https://testkru.com/Interactions/Alerts");

        // Listen for any alert/confirm/prompt dialogs and accept them
        page.onDialog(dialog -> {
            System.out.println("Message: " + dialog.message());
            dialog.dismiss(); // Dismisses the dialog (clicks "Cancel")
        });

        // Locate the alert trigger button using XPath
        Locator alertButton = page.locator("//button[@class='btn btn-info']");

        // Click the button to trigger the alert
        alertButton.click();

        // Close the browser instance
        browser.close();

        // Close Playwright engine
        playwright.close();
    }
}

Output –

Message: Do you want to proceed?

This confirms that the message was successfully retrieved. If you keep the browser open, you’ll also see ‘You clicked: Cancel’ displayed below the button you clicked, which proves that the popup was dismissed correctly.

Dismissed popup

Note: Similarly if we want to accept the popup, then we can use “dialog.accept()” funtion.

Unlike regular alerts, prompt dialogs not only display a message but also allow you to enter input text, as shown in the image below.

Dialog box

The dialog shown above will appear when you click on the element highlighted in the image below.

Dialog box trigger button

It’s simple, we’ll use the same dialog.accept() function, but this time we’ll also pass the input text as an argument to it.

dialog.accept("input_text");

Whole code

import com.microsoft.playwright.*;

public class CodekruTest {

    public static void main(String[] args) {

        // Start Playwright engine
        Playwright playwright = Playwright.create();

        // Launch Chromium browser in non-headless (visible) mode
        Browser browser = playwright.chromium().launch(
                new BrowserType.LaunchOptions().setHeadless(false)
        );

        // Create a new isolated browser context (like a fresh profile)
        BrowserContext context = browser.newContext();

        // Open a new tab (page) inside the context
        Page page = context.newPage();

        // Navigate to the Alerts test page
        page.navigate("https://testkru.com/Interactions/Alerts");

        // Listen for any alert/confirm/prompt dialogs and accept them
        page.onDialog(dialog -> {
            System.out.println("Message: " + dialog.message());
            dialog.accept("Codekru"); // Dismisses the dialog (clicks "Cancel")
        });

        // Locate the alert trigger button using XPath
        Locator alertButton = page.locator("//button[@class='btn btn-success']").nth(0);

        // Click the button to trigger the alert
        alertButton.click();

    }
}

Output –

Proof of dialog box code working

This shows that the code ran successfully.

  • Playwright offers a Dialog interface to handle alerts, confirmation boxes, and prompt dialogs.
  • We can subscribe to the dialog event to get the message and either accept or dismiss it.
  • Use dialog.accept() to accept the popup and dialog.dismiss() to dismiss it.
  • Use dialog.accept("input_text") to enter text into the dialog box.

We hope that you have liked the article. If you have any doubts or concerns, please write to us in the comments or mail us at admin@codekru.com.

Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *