
Vignesh Ambalam SureshWhen automating web applications, handling JavaScript alerts, confirms, and prompts is essential....
When automating web applications, handling JavaScript alerts, confirms, and prompts is essential. Here's how Playwright makes it straightforward:
Understanding Alert Types
Playwright automatically waits for dialogs and provides methods to interact with them. Use alert.type() to identify what you're dealing with:
alert - Simple information dialogs
confirm - Yes/No confirmation dialogs
prompt - Input request dialogs
beforeunload - Page navigation warnings
Reading Alert Content
Extract the message displayed in the dialog using alert.message(). This is particularly useful for assertions in your test scripts to verify expected behavior.
Accepting Alerts
Use alert.accept() to click "OK" or confirm the dialog. For prompt dialogs, you can pass input text: alert.accept('your input text').
Dismissing Alerts
Use alert.dismiss() to click "Cancel" or close the dialog without accepting. Note: This only works with confirm and prompt types.
Quick Implementation Example:
page.on('dialog', async dialog => {
console.log(`Dialog type: ${dialog.type()}`);
console.log(`Dialog message: ${dialog.message()}`);
if (dialog.type() === 'confirm') {
await dialog.accept();
} else {
await dialog.dismiss();
}
});
Pro Tip: Always set up dialog listeners before triggering the action that causes the alert. Playwright will fail the tests if a dialog appears without a registered handler.
What challenges have you faced with dialog handling in your automation journey? Share your experiences below!