Handling Alerts and Dialogs in Playwright
When automating web applications using Playwright, one common challenge is managing browser dialogs such as alerts, confirms, and prompts. These native dialogs can interrupt test execution if not handled properly. Fortunately, Playwright provides robust APIs to manage these scenarios efficiently.
What Are Browser Dialogs?
Dialog boxes are native pop-ups generated by JavaScript, typically used for:
alert(message) – Displays a message and waits for user to click OK.
confirm(message) – Asks for user confirmation (OK/Cancel).
prompt(message, default) – Requests user input.
Playwright's dialog Event
Playwright uses an event-based mechanism to detect and handle these dialogs. The page.on('dialog') event listens for any dialog that appears and allows you to control its behavior.
Example: Handling an Alert
page.on('dialog', async dialog => {
console.log('Dialog message:', dialog.message());
await dialog.accept();
});
await page.click('#trigger-alert');
In this example, Playwright listens for a dialog, prints its message, and accepts it automatically.
Example: Handling a Confirm Dialog
page.on('dialog', async dialog => {
console.log('Confirm message:', dialog.message());
await dialog.accept(); // To click OK
// await dialog.dismiss(); // To click Cancel
});
await page.click('#trigger-confirm');
You can choose to either accept (OK) or dismiss (Cancel) the confirm box.
Example: Handling a Prompt Dialog
page.on('dialog', async dialog => {
console.log('Prompt message:', dialog.message());
await dialog.accept('Playwright input'); // Provide input text
});
await page.click('#trigger-prompt');
With prompts, you can also send text input along with accepting the dialog.
Best Practices
Always listen for dialogs before triggering the action that causes them.
Handle the dialog event once per occurrence or use .once() to avoid unexpected behavior in multiple dialogs.
Use proper error handling in case dialogs are not triggered.
page.once('dialog', async dialog => {
await dialog.accept();
});
Conclusion
Handling browser dialogs in Playwright is simple and efficient using the dialog event. Whether you're testing user confirmations, alerts, or prompts, this event-based approach ensures your tests remain stable and uninterrupted.
Learn Playwright Training in Hyderabad
Read More:
How to Handle Dropdowns and Checkboxes
Parallel Testing with Playwright
Playwright CLI Commands You Should Know
Capturing Screenshots in Playwright
Visit our IHub Talent Training Institute
Comments
Post a Comment