How to Handle Web Overlays with Playwright's LocatorHandler
Ever feel like a whack-a-mole when unexpected elements like cookie consent popups disrupt your Playwright tests? You're not alone. These overlays can block actions and make tests unreliable. But fear not, Playwright's LocatorHandler comes to the rescue, offering a streamlined solution to handle these interruptions effectively.
What is addLocatorHandler?
Introduced in Playwright version 1.42, the addLocatorHandler method provides a mechanism to dynamically handle overlays that appear during automated testing. These overlays, like cookie consent dialogs, can block automated actions such as clicking buttons or filling out forms, making tests unreliable and cumbersome to maintain.
How does it work?
The addLocatorHandler method allows you to define a custom function that is triggered whenever a specified element locator is detected on the page. This function, known as a handler, is responsible for removing the overlay or taking any necessary actions to mitigate its impact on the test.
Example Usage:
Let's face a common foe: the cookie consent dialog. We can use addLocatorHandler to automatically dismiss it whenever it appears:
await page.addLocatorHandler(page.getByRole('button', { name: 'Accept all cookies' }), async () => {
await page.getByRole('button', { name: 'Reject all cookies' }).click();
});
await page.goto('https://example.com');
await page.getByRole('button', { name: 'Start here' }).click();
In this scenario, when the Accept all cookies button appears (our trigger), the handler function clicks the Reject all cookies button instead. This dismisses the dialog and allows your test to proceed as planned.
Benefits of addLocatorHandler:
Learn More:
For more details on using addLocatorHandler, refer to the official Playwright documentation: Here
Conclusion:
In conclusion, addLocatorHandler simplifies handling overlays in Playwright tests, boosting test reliability and efficiency. It empowers testers to focus on core test logic without worrying about unexpected interruptions.
Senior Automation Test Engineer @ Wipro Limited | Playwright | Webdriver IO | BDD Cucumber | JavaScript | TypeScript | Selenium | Java | UI Testing | UAT | CICD
4moHelpful! Just to add to it, we need to add the locator handler to the new page if a new page is opened during test.