Handle Alerts in Playwright
























How to Handle Alert Popups in Playwright Java (Alert, Confirm, Prompt)

Handling alert popups is one of the most common scenarios in web automation. When working with Playwright Java, you will often encounter JavaScript dialogs such as alerts, confirm boxes, and prompt popups. These dialogs block user interaction until handled properly.

In this tutorial, you will learn how to handle alerts in Playwright Java step by step with real examples, explanations, and best practices.


What Are JavaScript Alerts?

JavaScript alerts are modal dialog boxes that appear on a web page to display information or request user confirmation. Because they are modal, they pause page execution until the user interacts with them.

There are three main types of JavaScript dialogs:

1️⃣ Alert

  • Displays a message.

  • Has only one button: OK.

2️⃣ Confirm

  • Displays a message.

  • Has two buttons: OK and Cancel.

3️⃣ Prompt

  • Displays a message.

  • Allows user input.

  • Has OK and Cancel buttons.

In automation, these dialogs must be handled programmatically.


How Alerts Work in Playwright Java

In Playwright Java, alerts trigger a dialog event on the Page object.

To handle them, we use:

page.onDialog(handler);

This method listens for dialog events and allows us to:

  • Accept the alert

  • Dismiss the alert

  • Provide input to prompt dialogs

  • Capture the alert message


Methods Used to Handle Alerts

Here are the key methods used in Playwright:

  • dialog.accept() → Clicks OK

  • dialog.dismiss() → Clicks Cancel

  • dialog.accept("text") → Sends input to prompt

  • dialog.message() → Retrieves alert message


Important Points About Alerts in Playwright

Before writing code, keep these important points in mind:

  • Alerts block page interaction until handled.

  • You must set up the dialog listener before triggering the alert.

  • If alerts are not handled properly, the script may timeout.

  • Always handle alerts in the same execution flow that triggers them.


Handling Alert Popup in Playwright Java – Practical Example

We will use this sample website for demonstration:

https://the-internet.herokuapp.com/javascript_alerts

This website contains examples of JavaScript Alert, Confirm, and Prompt popups.


Complete Code Example – Handle Alert in Playwright Java

import com.microsoft.playwright.*; public class HandleAlertPopup { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { // Launch browser Browser browser = playwright.chromium() .launch(new BrowserType.LaunchOptions().setHeadless(false)); Page page = browser.newPage(); // Set up dialog handler page.onDialog(dialog -> { System.out.println("Dialog message: " + dialog.message()); dialog.accept(); // dialog.dismiss(); // Use this for cancel // dialog.accept("Your input"); // For prompt }); // Navigate to website page.navigate("https://the-internet.herokuapp.com/javascript_alerts"); // Trigger JavaScript Alert page.locator("text=Click for JS Alert").click(); // Capture result message String result = page.locator("#result").textContent(); System.out.println("Result after handling alert: " + result); browser.close(); } } }


Code Explanation (Step-by-Step)

Step 1: Launch Playwright

We initialize the Playwright engine using:

Playwright.create()

This sets up the automation environment.


Step 2: Launch the Browser

We launch the Chromium browser:

playwright.chromium().launch()

You can also use:

  • playwright.firefox()

  • playwright.webkit()


Step 3: Create Page Instance

Page page = browser.newPage();

This creates a new browser tab.


Step 4: Add Dialog Listener

page.onDialog(dialog -> { System.out.println(dialog.message()); dialog.accept(); });

This listener automatically captures and handles any dialog that appears.


Step 5: Trigger the Alert

page.locator("text=Click for JS Alert").click();

This action triggers the alert popup.


Step 6: Capture Result Text

page.locator("#result").textContent();

After accepting the alert, we verify the success message displayed on the page.


Sample Output

Dialog message: I am a JS Alert Result after handling alert: You successfully clicked an alert


Handling Confirm Dialog in Playwright Java

To dismiss a confirm popup (click Cancel), modify the dialog handler:

page.onDialog(dialog -> { System.out.println(dialog.message()); dialog.dismiss(); });

This simulates clicking the Cancel button.


Handling Prompt Dialog in Playwright Java

To send input to a prompt dialog:

page.onDialog(dialog -> { System.out.println(dialog.message()); dialog.accept("Automation Test"); });

This sends text into the prompt input field before clicking OK.


Best Practices for Handling Alerts in Playwright

✔ Always define page.onDialog() before clicking the element that triggers the alert.

✔ Keep alert handling logic close to the action that triggers it.

✔ Avoid hard-coded waits; rely on Playwright's built-in event handling.

✔ Log alert messages for debugging purposes.

✔ Test both accept and dismiss scenarios for confirm dialogs.


Why Handling Alerts Is Important in Automation?

In real-world applications:

  • Login pages may display alerts for incorrect credentials.

  • Payment systems may show confirmation dialogs.

  • Forms may trigger validation popups.

  • Applications may use prompt dialogs for user input.

Without proper alert handling, your automation script will fail.


Frequently Asked Questions (FAQs)

Q1: What happens if I don’t handle alerts in Playwright?

The script may hang or timeout because alerts block page execution.

Q2: Does Playwright automatically accept alerts?

No. You must explicitly handle them using page.onDialog().

Q3: Can I capture alert text in Playwright Java?

Yes. Use dialog.message() to retrieve the alert text.

Q4: Can Playwright handle multiple alerts?

Yes. The dialog listener will handle every dialog triggered on the page.


Conclusion

Handling alert popups in Playwright Java is straightforward once you understand the dialog event mechanism. By using page.onDialog(), you can:

  • Accept alerts

  • Dismiss confirm dialogs

  • Send input to prompt dialogs

  • Capture alert messages

Mastering alert handling is essential for building reliable UI automation frameworks in Playwright.

Suggested Posts:

1. Playwright with TestNG Integration
2. BrowserContext in Playwright
3. Handle Dropdowns in Playwright
4. Handle IFrames in Playwright
5. Page Object Model in Playwright

No comments:

Post a Comment