Injected Scripts
Relevant source files
The following files were used as context for generating this wiki page:
Injected scripts are a core component of Playwright's architecture, consisting of JavaScript code that is executed within the context of the browser page. This allows Playwright to perform complex operations and gather detailed information directly from the DOM, which would be inefficient or impossible from the Node.js environment. These scripts are responsible for a wide range of functionalities, including selector evaluation, action recording, and accessibility analysis.
The injected script is created by bundling several TypeScript modules into a single JavaScript string. This bundle is then injected into every frame of the page, creating a window.__injectedScript object that exposes various utilities. This mechanism is fundamental to features like the Codegen and the powerful, web-first selector engine.
Architecture and Build Process
The injected script is not a single file but a collection of modules bundled together. The build process is managed by a custom Node.js script.
Build Process
The utils/generate_injected.js script is responsible for creating the final injected script string. It reads multiple source files from the packages/injected/src/ directory, concatenates them, and wraps them in an IIFE (Immediately Invoked Function Expression) to avoid polluting the global scope of the target page. The output is a single string that can be efficiently injected and evaluated by the browser.
This diagram illustrates the build process for the injected script.
Sources: utils/generate_injected.js
Injection and Execution
Once built, the script is injected into the target page. A primary way for users to leverage this mechanism is through the page.addInitScript() method, which allows custom scripts to be evaluated before any other script on the page. This is particularly useful for setting up the page environment, mocking APIs, or defining global helper functions.
Tests confirm that these init scripts run before any other page scripts, can be sourced from a file path or a content string, and work correctly even with Content Security Policies (CSP).
Sources: tests/page/page-add-init-script.spec.ts:15-18, tests/page/page-add-init-script.spec.ts:20-24, tests/page/page-add-init-script.spec.ts:40-44
Core Modules
The injected script is composed of several key modules, each with a specific responsibility.
| Module | Description | Source File |
|---|---|---|
injectedScript | The main entry point. It creates the window.__injectedScript object and exposes utilities for other modules. | packages/injected/src/injectedScript.ts |
recorder | Contains the logic for the Playwright test recorder (Codegen). It listens for user interactions and generates corresponding Playwright code. | packages/injected/src/recorder/recorder.ts |
selectorEvaluator | Implements the client-side logic for Playwright's selector engines, enabling queries like getByRole, getByText, etc. | packages/injected/src/selectorEvaluator.ts |
utils | A collection of helper functions used by other injected modules, such as for calculating element accessibility names and roles. | tests/library/role-utils.spec.ts:14-18 |
Selector Engine
The selectorEvaluator.ts module is a critical part of the injected script. It allows Playwright to execute complex selector queries directly in the browser.
Key functions include:
querySelector(selector: string, root: Node): Element | undefined: Finds the first element matching the selector.querySelectorAll(selector: string, root: Node): Element[]: Finds all elements matching the selector.
This client-side evaluation is what powers Playwright's advanced selectors, including role, text, and test-id locators. The generateSelector function is also part of this system, which can generate a unique selector for a given target element, a feature used by Codegen.
Sources: packages/injected/src/selectorEvaluator.ts, tests/library/selector-generator.spec.ts:13-18
Recorder (Codegen)
The recorder.ts module provides the client-side intelligence for Playwright's test recorder. It attaches event listeners to the document to capture user actions and then communicates these actions back to the Playwright process.
The following sequence diagram shows how a user click is captured and processed by the injected recorder script.
This diagram illustrates the flow of a user interaction being captured by the injected recorder script and sent to the Playwright backend for code generation.
The recorder listens for a variety of events, including click, input, keydown, and scroll, to provide comprehensive recording capabilities.
Sources: packages/injected/src/recorder/recorder.ts:108-121
Accessibility Utilities
The injected script includes a suite of utility functions for determining the accessibility properties of DOM elements. These are used internally by role-based selectors and assertions.
Functions like getElementAccessibleName and getAriaRole are exposed on the window.__injectedScript.utils object. These functions implement the logic defined in the W3C's ARIA and Accessible Name specifications. Tests for these utilities are run against the official Web Platform Tests (WPT) to ensure compliance.
// Example from tests/library/role-utils.spec.ts
async function getNameAndRole(page: Page, selector: string) {
return await page.$eval(selector, e => {
const name = (window as any).__injectedScript.utils.getElementAccessibleName(e);
const role = (window as any).__injectedScript.utils.getAriaRole(e);
return { name, role };
});
}
Sources: tests/library/role-utils.spec.ts:13-20
Summary
Injected scripts are a cornerstone of Playwright's functionality, enabling direct and efficient interaction with the browser's DOM. By bundling and injecting a suite of specialized modules, Playwright can offer advanced features such as a powerful selector engine, a robust test recorder, and accurate accessibility analysis. The page.addInitScript API also exposes this powerful injection mechanism to users, allowing for extensive customization of the testing environment.