🚨 Playwright Actions #25 Handling JavaScript Alerts with page.on('dialog')
In this tutorial, we explore how to handle JavaScript simple alerts in Playwright—those classic pop-ups with a message and an “OK” button. These alerts can block test execution if not handled properly, so mastering this interaction is key to building stable automation flows.
🎯 What You’ll Learn:
🧠 What is a JS Simple Alert?
→ A modal dialog triggered by alert() in JavaScript.
→ Contains a message and a single “OK” button.
→ Blocks page interaction until dismissed.
🛠️ Handling Alerts with page.on('dialog')
→ Register a listener before the action that triggers the alert:
page.on('dialog', async dialog {
expect(dialog.message()).toBe('I am a JS Alert');
await dialog.accept();
});
await page.getByText('Click for JS Alert').click();
→ Use dialog.accept() to close the alert and continue execution.
✅ Validating Post-Alert Behavior
→ Confirm that the alert was handled correctly using assertions:
expect(page.locator('#result')).toHaveText('You successfully clicked an alert')
⚠️ Common Pitfalls & Fixes
→ Always set the dialog listener before triggering the alert.
→ Without a listener, Playwright auto-dismisses alerts, which may cause missed validations.
→ Use trace viewer to inspect dialog flow and ensure proper sequencing.
🧪 Real-World Use Cases
Confirming user actions (e.g., delete confirmation)
Alerting users of form errors
Triggering warnings before navigation or submission
#playwright #JavaScriptAlert #DialogHandling #AutomationTesting #QAEngineer #WebAutomation #PlaywrightTutorial #SDET #TypeScriptTesting