Saturday, May 24, 2025

Use Playwright's addLocatorHandler to close unpredictable UI elements

In this example we will explore how to use addLocatorHandler in playwright. Playwright’s addLocatorHandler is a powerful tool for handling unpredictable UI elements, such as popups, cookie banners, or modals, that may appear during test execution. It allows you to define custom logic to interact with elements identified by a locator, automatically executing when the element becomes visible. Below, I’ll explain how to use addLocatorHandler to close such UI elements, with concise examples in JavaScript.

NOTE : This feature is added in playwright 1.42

Use Playwright's addLocatorHandler to close unpredictable UI elements


Point to remember while using addLocatorHandler 

Purpose: addLocatorHandler registers a handler for a specific locator (e.g., a button or banner). When the element appears, Playwright triggers the handler to perform actions like clicking a "Close" button.

Usage: It’s ideal for handling dynamic UI elements that may or may not appear, ensuring tests remain robust without manual checks for element visibility.

Scope: The handler runs whenever the locator becomes visible during the test lifecycle, until it’s removed.


Closing a Cookie Banner using addLocatorHandler

Suppose a website displays a cookie consent popup with an "Accept" or "Close" button. Here’s how to use addLocatorHandler to close it automatically.

const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch({ headless: false });
  const page = await browser.newPage();

  // Register handler for cookie banner close button
  await page.addLocatorHandler(
    page.locator('#cookie-banner .close-button'), // Locator for the close button
    async (locator) => {
      console.log('Cookie banner detected, closing...');
      await locator.click(); // Click the close button
    }
  );

  // Navigate to a website
  await page.goto('https://example.com');

  // Perform other test actions
  await page.click('#some-element');
  
  await browser.close();
})();

Handling Multiple Attempts using addLocatorHandler

Sometimes, a click may not dismiss the element due to animations or delays. You can add retry logic in the handler.
const { chromium } = require('playwright');

(async () => {
  const browser = await chromium.launch({ headless: false });
  const page = await browser.newPage();

  // Register handler with retry logic
  await page.addLocatorHandler(
    page.locator('.popup .dismiss-button'),
    async (locator) => {
      console.log('Popup detected, attempting to close...');
      for (let attempt = 0; attempt < 3; attempt++) {
        try {
          await locator.click({ timeout: 2000 }); // Click with timeout
          console.log('Popup closed successfully');
          return;
        } catch (error) {
          console.log(`Attempt ${attempt + 1} failed: ${error.message}`);
          await page.waitForTimeout(1000); // Wait before retrying
        }
      }
      console.log('Failed to close popup after retries');
    }
  );

  // Navigate to a website
  await page.goto('https://example.com');

  // Other test actions
  await page.fill('#search-input', 'Playwright');
  await page.click('#submit-button');

  await browser.close();
})();

This is all about basic implementation of addLocatorHandler function in playwright.


No comments:

Post a Comment