Extensibility

Custom selector engines

Playwright supports custom selector engines, registered with selectors.register(name, script[, options]).

Selector engine should have the following properties:

  • create function to create a relative selector from root (root is either a Document, ShadowRoot or Element) to a target element.
  • query function to query first element matching selector relative to the root.
  • queryAll function to query all elements matching selector relative to the root.

By default the engine is run directly in the frame’s JavaScript context and, for example, can call an application-defined function. To isolate the engine from any JavaScript in the frame, but leave access to the DOM, register the engine with {contentScript: true} option. Content script engine is safer because it is protected from any tampering with the global objects, for example altering Node.prototype methods. All built-in selector engines run as content scripts. Note that running as a content script is not guaranteed when the engine is used together with other custom engines.

An example of registering selector engine that queries elements based on a tag name:

  1. // Must be a function that evaluates to a selector engine instance.
  2. const createTagNameEngine = () => ({
  3. // Creates a selector that matches given target when queried at the root.
  4. // Can return undefined if unable to create one.
  5. create(root, target) {
  6. return root.querySelector(target.tagName) === target ? target.tagName : undefined;
  7. },
  8. // Returns the first element matching given selector in the root's subtree.
  9. query(root, selector) {
  10. return root.querySelector(selector);
  11. },
  12. // Returns all elements matching given selector in the root's subtree.
  13. queryAll(root, selector) {
  14. return Array.from(root.querySelectorAll(selector));
  15. }
  16. });
  17. // Register the engine. Selectors will be prefixed with "tag=".
  18. await selectors.register('tag', createTagNameEngine);
  19. // Now we can use 'tag=' selectors.
  20. const button = await page.$('tag=button');
  21. // We can combine it with other selector engines using `>>` combinator.
  22. await page.click('tag=div >> span >> "Click me"');
  23. // We can use it in any methods supporting selectors.
  24. const buttonCount = await page.$$eval('tag=button', buttons => buttons.length);