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
pathto a JavaScript file orcontentwith the code
boolean
default:"false"
Whether to run the selector engine script as a content script in the page context. Only applies to Chromium.
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 forgetByTestId() locators.
string
required
Attribute name to use for test ID selectors
void
By default, Playwright uses data-testid attribute. Change it to match your project’s convention:
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
Related
- Locators - Element location API
- Built-in Selectors - Playwright’s default selectors
