🛑 Playwright Actions #26 Handling JavaScript Confirm Alerts with Precision
In this tutorial, we explore how to automate JavaScript confirmation alerts using Playwright’s page.on('dialog') listener. These alerts are triggered by confirm() in JavaScript and require a decision—either accept or dismiss. Whether you're testing delete confirmations or navigation warnings, this skill is essential for bulletproof automation.
🎯 What You’ll Learn:
⚙️ What is a JS Confirm Alert?
→ A modal dialog with a message and two buttons: “OK” and “Cancel”
→ Blocks page interaction until handled
🛠️ Handling Confirm Alerts with Playwright
→ Use page.on('dialog') to intercept and respond to the alert
→ Accept the alert:
page.on('dialog', async dialog = {
expect(dialog.message()).toBe('I am a JS Confirm');
await dialog.accept();
});
→ Dismiss the alert:
page.on('dialog', async dialog = {
expect(dialog.message()).toBe('I am a JS Confirm');
await dialog.dismiss();
});
✅ Validating Outcomes
→ After accepting:
expect(page.locator('#result')).toHaveText('You clicked: Ok')
→ After dismissing:
expect(page.locator('#result')).toHaveText('You clicked: Cancel')
⚠️ Best Practices
→ Always register the dialog listener before triggering the alert
→ Use expect(dialog.message()) to validate the alert content
→ Avoid flaky tests by sequencing actions carefully
🧪 Real-World Use Cases
Confirming deletion of records
Navigating away from unsaved forms
Accepting terms before proceeding
Triggering conditional logic based on user confirmation
#playwright #JSConfirmAlert #DialogHandling #AutomationTesting #QAEngineer #WebAutomation #PlaywrightTutorial #SDET #TypeScriptTesting