Rayrun

What is the process of adding custom functions to the Locator class in Playwright?

Answer

Extending Locators with Custom Functions in Playwright

You can add your own methods to the Locator class in Playwright by extending it. Let's create a custom function that checks if an element is visible.

First, define your function. Here's an example:

function isVisible(this: Locator): Promise<boolean> {
  return this.evaluate((element) => {
    const style = window.getComputedStyle(element);
    return style && style.display !== 'none' && style.visibility !== 'hidden' && element.offsetHeight > 0;
  });
}

This function returns a promise that resolves to true if the element is visible and false otherwise.

Next, extend the Locator class to include your custom function:

class CustomLocator extends Locator {
  async isVisible(): Promise<boolean> {
    return this.evaluate((element) => {
      const style = window.getComputedStyle(element);
      return style && style.display !== 'none' && style.visibility !== 'hidden' && element.offsetHeight > 0;
    });
  }
}

Now, you can use your custom locator like this:

const button = await page.locator('button').isVisible();
if (button) {
  await button.click();
}

Remember not to override existing methods or properties of the Locator class. Also, test your custom functions thoroughly before using them in production code.

In short, extending locators with custom functions in Playwright involves defining your own JavaScript functions and adding them as methods of the Locator class using inheritance. This allows you to create more expressive and reusable locators for your tests.

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.