Skip to main content
The Selectors API allows you to register custom selector engines that can be used throughout Playwright to locate elements.

Overview

Playwright supports multiple built-in selector engines (CSS, XPath, text, etc.). You can extend this with custom selector engines to match elements based on your own logic.

Methods

register(name, script, options)

Register a custom selector engine.
string
required
Name of the selector engine. Once registered, you can use it with the syntax name=selector.
string | Function | { path?: string, content?: string }
required
Script that evaluates to a selector engine instance. Can be:
  • A function that returns a selector engine
  • A string containing JavaScript code
  • An object with path to a JavaScript file or content with the code
boolean
default:"false"
Whether to run the selector engine script as a content script in the page context. Only applies to Chromium.
Returns: Promise<void>

Selector Engine Interface

Your selector engine must implement:

Example: Tag Name Selector

Example: Data Attribute Selector

Example: Loading from File

setTestIdAttribute(attributeName)

Set the attribute name to use for getByTestId() locators.
string
required
Attribute name to use for test ID selectors
Returns: void By default, Playwright uses data-testid attribute. Change it to match your project’s convention:
You can also configure this in playwright.config.ts:

Complete Example

Best Practices

Selector Engine Naming

  • Use descriptive names that indicate what the selector matches
  • Avoid names that conflict with built-in engines (css, xpath, text, etc.)
  • Use lowercase names for consistency

Error Handling

Performance

  • Keep selector logic simple and fast
  • Avoid expensive computations in queryAll
  • Cache results when appropriate

Limitations

  • Custom selectors cannot be registered after tests have started
  • Each selector engine name can only be registered once
  • Content script mode only works in Chromium