Handle Alerts in Playwright

 

Handling alert popups (JavaScript alerts, confirms, prompts) in Playwright Java involves listening for the Dialog event on the Page object. When a JavaScript alert, confirm, or prompt appears on a webpage, Playwright can catch it using a listener and either accept or dismiss it accordingly.
















Types of JavaScript Dialogs

  • Alert → Only one button: OK
  • Confirm → Two buttons: OK and Cancel
  • Prompt → Input + OK/Cancel

Concept

  • page.onDialog(handler) allows us to listen to dialog events.

  • Use dialog.accept() to accept it.

  • Use dialog.dismiss() to dismiss it.

  • Use dialog.accept("input") to send input to prompt dialogs.



Handling Alert Popup in Playwright Java

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

Code Example:



import com.microsoft.playwright.*;

public class HandleAlertPopup {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            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();  // Accept the alert
                // dialog.dismiss(); // Use this for cancel
                // dialog.accept("Your input"); // For prompt dialog input
            });

            // Navigate to page with alert
            page.navigate("https://the-internet.herokuapp.com/javascript_alerts");

            // Click the button to trigger alert
            page.locator("text=Click for JS Alert").click();

            // Optional: Wait for result text
            String result = page.locator("#result").textContent();
            System.out.println("Result after handling alert: " + result);

            browser.close();
        }
    }
}




Output:


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

No comments:

Post a Comment