Playwright Tips: How to Handle Alerts the Right Way
Alert Handling in Playwright In Playwright, JavaScript alerts, confirmation dialogs, and prompts are collectively called Dialogs. What happens if we don't handle an Alert? If there is no dialog listener registered, Playwright automatically dismisses the dialog. So, if you want to explicitly accept, dismiss, validate, or provide input to a dialog, you need to handle it. How do we handle Alerts? Playwright provides the `page.on('dialog')` event to handle JavaScript dialogs. `page.on('dialog', handler); Let's understand what is happening here. 1. `page.on('dialog')` subscribes to the dialog event page.on('dialog', ...) Here, `page.on()` is used to subscribe/listen for an event. In this case, we are listening for the `dialog` event. 2. When the Alert appears, the dialog event is triggered When the application opens a JavaScript alert: alert("Hello Prince"); Playwright detects the dialog and triggers the `dialog` event. 3. Playwright invokes the handler The second argument of `page.on()` is a callback function, commonly referred to as an event handler. `page.on('dialog', handler); This function is automatically called when the `dialog` event is triggered. What is a Handler? A handler is a callback function that contains the logic to execute when a particular event occurs. The `dialog` object passed to this handler represents the JavaScript dialog that was triggered. Inside the handler, we can decide what action to perform. Accept the Alert Dismiss the Dialog Enter a value in a Prompt Get the Alert Message So the overall flow is: Application → Alert appears → Playwright detects Dialog → `dialog` event is triggered → Handler is invoked → Handling logic executes** The important thing to remember is: page.on('dialog')` listens for the dialog event, and the callback function acts as the event handler where we write our dialog-handling logic. Regards, PrinceAutomationDestination 0:00 Understanding Web Alerts in Playwright 0:46 Mastering Dialogue Event Handling 1:58 Implementing Alert Logic in Tests 7:13 Pro Tips for Advanced Alert Management




Join the discussion
Sign in to join the discussion
Sign in