--- title: Browser description: The browser engine, its options, and the browser fixture it contributes. "og:image": "https://e2e.com/docs/images/og/reference/web.png?v=66fee465a4" "twitter:image": "https://e2e.com/docs/images/og/reference/web.png?v=66fee465a4" --- `@e2e-dev/web` is the browser engine. It drives Chromium, Firefox, and WebKit through Playwright. A web target names it as its engine with `web()`, and it contributes the built-in `browser` fixture for browser-only work. ```ts title="e2e.config.ts" import type { E2EConfig } from 'e2e'; import { web } from '@e2e-dev/web'; export default { targets: [{ engine: web(), app: { url: 'http://localhost:3000' } }], } satisfies E2EConfig; ``` Import `test` from the package to have `browser` typed: ```ts title="tests/orders.e2e.ts" import { expect } from 'e2e'; import { test } from '@e2e-dev/web'; test('orders in dark mode', async ({ app, browser, screen }) => { await browser.emulateMedia({ colorScheme: 'dark' }); await app.open('/orders'); await expect(browser).toHaveURL('/orders'); await expect(screen.getByRole('heading', { name: 'Orders' })).toBeVisible(); }); ``` ## Reference ### Options `web(options)` sets how the engine drives the app. The app itself (its `url`, `environment`, `identity`, and the command that starts it) is the target's `app`, documented under [the app under test](/reference/config#the-app-under-test). ```ts web({ viewport: { width: 390, height: 844 }, locale: 'de-DE' }); ``` | Option | Type | Default | | --- | --- | --- | | [`browser`](#browser) | `BrowserName \| BrowserProvider` | `'chromium'` | | [`chromiumSandbox`](#chromiumsandbox) | `boolean` | `true`, `false` on Linux | | [`viewport`](#viewport) | `ViewportSize \| null` | 1280 by 720 | | [`deviceScaleFactor`](#devicescalefactor) | `number` | `1` | | [`screencast`](#screencast) | `WebScreencastOptions` | the viewport's size | | [`connect`](#connect) | `WebConnectOptions` | launches locally | | [`headers`](#headers) | `Record` | - | | [`basicAuth`](#basicauth) | `WebBasicAuth` | - | | [`credentialOrigins`](#credentialorigins) | `string[]` | - | | [`testIdAttribute`](#testidattribute) | `string` | `'data-testid'` | | [`userAgent`](#useragent) | `string` | the browser's own | | [`locale`](#locale) | `string` | the browser's own | | [`timezoneId`](#timezoneid) | `string` | the machine's | | [`colorScheme`](#media-emulation) | `'light' \| 'dark' \| 'no-preference'` | the browser's own | | [`reducedMotion`](#media-emulation) | `'reduce' \| 'no-preference'` | the browser's own | | [`initScripts`](#init-scripts) | `WebInitScript[]` | - | | [`webmcp`](#webmcp) | `boolean` | `false` | - A `web()` target needs `app.url` and refuses the device keys (`bundleId`, `appPath`, `launchArguments`). Its `app.permissions` takes `'grant'` only, for names its browser grants, or `'all'` for every one; see [`permissions`](/reference/config#permissions). - The full declaration with its JSDoc is [`WebOptions`](#weboptions) under Types. | Throws | When | | --- | --- | | `INVALID_CONFIG` | An option `web()` does not take (`url` or any other app key included), or an unknown key inside `connect` or `basicAuth`. The message names the nearest known key for a likely typo (`viewprt` is `viewport`), or lists every key. | | `INVALID_CONFIG` | A browser provider, `connect`, `headers`, or `basicAuth` on a target whose [`app.url` is a file](/reference/config#a-file-as-the-app). | | `INVALID_CONFIG` | `headers`, `basicAuth`, `userAgent`, `locale`, `timezoneId`, or `deviceScaleFactor` on a [persistent context](#recovering-a-cdp-transport) (`connect.reconnectEndpoint`, or a provider with `scope: 'attempt'`). | #### `browser` The browser to launch, or a provider that leases hosted browsers. ```ts web({ browser: 'firefox' }); // default: 'chromium' ``` - `'chromium'`, `'firefox'`, or `'webkit'`. - A `BrowserProvider` leases hosted browsers instead: one per worker slot for the run, or one per attempt ([`WebOptions`](#weboptions)). The engine drives each one as chromium over CDP, whether it is Chromium or another CDP server such as [Lightpanda](/integrations/lightpanda) or [Moli](/integrations/moli). - A provider with `scope: 'attempt'` rides a persistent context, with the limits under [Recovering a CDP transport](#recovering-a-cdp-transport). - [Hosted browsers](/browser#hosted-browsers) has the `BrowserProvider` contract and an example provider. | Throws | When | | --- | --- | | `INVALID_CONFIG` | `browser: provider` together with `connect`. | | `INVALID_CONFIG` | A name other than `'chromium'`, `'firefox'`, or `'webkit'`, or a value that is neither a name nor a provider. | #### `chromiumSandbox` Whether a locally launched Chromium runs with its OS sandbox on. ```ts web({ chromiumSandbox: true }); // default: true on macOS and Windows, false on Linux ``` - The sandbox helps contain a renderer exploit on a page the agent reaches; see [Security](/security). - On Linux the sandbox needs unprivileged user namespaces, which root, most containers, and Ubuntu 23.10+ block. Set `true` on a host that allows them. - A browser reached through `connect` or a provider is launched by its host, and Firefox and WebKit have no such option, so none of them read it. | Throws | When | | --- | --- | | `INVALID_CONFIG` | Any value that is not a boolean, at config load. | | `ENGINE_FAILURE` | The sandbox is on and cannot start on this host. | #### `viewport` The initial viewport of every attempt's page. ```ts web({ viewport: { width: 390, height: 844 } }); // default: { width: 1280, height: 720 } ``` `null` emulates no size, so the page fills the browser window ([`WebOptions`](#weboptions)). [`browser.setViewport`](#setviewport) still fixes one. | Throws | When | | --- | --- | | `INVALID_CONFIG` | A value that is not `null` or `{ width, height }` in whole pixels, each at least 1, or a size with any other key. | #### `deviceScaleFactor` Device pixels per CSS pixel on every attempt's page, as `window.devicePixelRatio` reads it. ```ts web({ deviceScaleFactor: 2 }); // default: 1 ``` - Saved screenshots are in device pixels: [`app.screenshot()`](/reference/app#screenshot), a failure's, and an `agent.assert`'s. At 2, a 1280 by 720 viewport makes a 2560 by 1440 file. - The factor does not change the image the model reads or the one [`toHaveScreenshot`](/reference/expect#tohavescreenshot) compares. | Throws | When | | --- | --- | | `INVALID_CONFIG` | A value that is not a number above 0, or one beside `viewport: null`. | #### `screencast` How the engine's own screencast records an attempt that records video. ```ts web({ screencast: { size: { width: 800, height: 450 }, quality: 60 } }); ``` - `size` takes whole pixels, each side at least 1. `quality` is an integer. - Which attempts record is the config's [`video`](/reference/config#video) mode. ```ts /** The engine's screencast of the page: the frame size and the JPEG quality of the frames it encodes. */ export interface WebScreencastOptions { /** Frame size in pixels; default the viewport's, or the window's under `viewport: null`. A smaller size makes a smaller file. */ readonly size?: ViewportSize; /** JPEG quality of each captured frame, 0 through 100; Playwright's default when unset. */ readonly quality?: number; } ``` | Throws | When | | --- | --- | | `INVALID_CONFIG` | Any other `size` or `quality` value, or another key, at config load. The old `web({ video })` spelling is also refused, naming `screencast`. | #### `connect` Attaches to a remote browser over CDP instead of launching one locally. ```ts web({ connect: { cdpEndpoint: async () => 'ws://127.0.0.1:9222' } }); ``` `reconnectEndpoint` opts into a persistent context; see [Recovering a CDP transport](#recovering-a-cdp-transport). Either resolver can return `{ endpoint, headers }` as a `CdpTarget` to authenticate the CDP handshake. These headers are separate from `web({ headers })`, which sends headers to the app. ```ts interface WebConnectOptions { cdpEndpoint(signal: AbortSignal): string | CdpTarget | Promise; reconnectEndpoint?(signal: AbortSignal): string | CdpTarget | Promise; } ``` | Throws | When | | --- | --- | | `INVALID_CONFIG` | A `connect` without `cdpEndpoint`, or with one given as a string, at config load. Also `connect` beside a `browser` provider. | ##### Recovering a CDP transport `connect.reconnectEndpoint(signal)` opts into recovery of the same remote browser after its CDP transport disconnects. Omit it to keep isolated contexts. The remote browser: - Every attempt, retries included, needs its own fresh browser from `cdpEndpoint`. One long-lived browser cannot serve a suite. - The remote must have only its default context. - The host must delete the browser when the attempt ends. Engine cleanup detaches its connection and does not terminate the host's browser. - The attempt's first page is the browser's own first tab, navigated to `about:blank`, not a second tab beside it. A page opened later, such as the one `app.restart` opens, is a new tab. How recovery runs: - After a disconnect, the next operation calls `reconnectEndpoint` once, within that operation's timeout and abort signal. The resolver must return the existing browser's endpoint. - The engine checks the persistent default context ID and the active tab's target ID. It refuses a browser that does not expose the default context ID. A missing active tab or a different context fails the attempt. A matching URL does not select a replacement tab. The attempt's other tabs are found by their target IDs; one that is gone is dropped. - The engine installs secure-field masking before it publishes each CDP binding. An incompatible Playwright version fails the connection instead of exposing pixels. - The original page's frames must keep their closed shadow DOM tracking hooks. Existing closed roots cannot recover without a reload of the application. Mask queries reject any untracked document. - Endpoint resolution, CDP attachment, setup, and dispatch share one timeout. Cancelling a concurrent waiter does not cancel the operation that started recovery. Cancelling that recovery owner fails the shared recovery. | Throws | When | | --- | --- | | `ENGINE_FAILURE` | A document loaded without the closed shadow DOM hook while disconnected, or the attempt used [`browser.clock`](#clock), which recovery cannot carry. | | `OPERATION_TIMEOUT` | Endpoint resolution, attachment, setup, and dispatch exhausted their shared timeout. | | `CANCELLED` | The caller or the attempt cancelled. | What survives: - Recovery keeps the page's unsaved state, storage, and the agent ledger. Dialog and route handlers are reattached. - Video recording resumes. A segment lost during the disconnect is gone. - Operations already dispatched are never retried. - Recovery clears old node references. Observation-derived `tapAt` and `doubleTapAt` calls, observation-root swipes, and focused engine keyboard input need a fresh engine observation before they resume. - An observation or locator read started before recovery cannot publish references after the connection changes. Each attempt owns its binding and recordings, so late cleanup cannot change a later attempt. - The deterministic `browser.mouse` and `browser.keyboard` fixtures stay available without an agent observation. Test code owns its input and can read current geometry and focus with `browser.evaluate` before acting. - Code that uses `surfaceOf(engine)` must read its accessors again after recovery. Playwright objects it kept belong to the disconnected transport. A `browser` provider with `scope: 'attempt'` rides the same persistent context, with the same limits. The lease's `cdpEndpoint` provisions the attempt's browser, and its `reconnectEndpoint` (or `cdpEndpoint` again) reconnects to it. A lease is fresh by the provider's contract, so the engine does not compare its context with earlier attempts'. A hosted service may restore browsers from one snapshot, which gives new browsers the same context id. To reuse one sign-in across files, keep isolated contexts (no `reconnectEndpoint`, no provider `scope: 'attempt'`) and [sign in once in a setup test](/authentication#reuse-authenticated-sessions). A saved session carries it, not a shared browser. A persistent context does not support `headers`, `basicAuth`, `userAgent`, `locale`, `timezoneId`, `deviceScaleFactor` (see [Options](#options)), `app.clearState`, or session state capture and restore. `app.clearState` fails with `UNSUPPORTED_CAPABILITY`. `app.restart` remains available. #### `headers` Headers added to every request that starts at the app's origin: the scheme, host, and port of `app.url`. A request that starts at another port, a subdomain, or any other host gets none. A redirect keeps the headers its request started with, to any origin. ```ts web({ headers: { 'x-preview-token': process.env.PREVIEW_TOKEN ?? '' } }); ``` - A [continued](#route) request bound for an allowed origin still carries them. - `headers` and `basicAuth` are how a test reaches a [protected preview](/web#protected-previews). - See [request credentials](/reference/security#request-credentials). | Throws | When | | --- | --- | | `INVALID_CONFIG` | A `user-agent` entry beside [`userAgent`](#useragent), or an `accept-language` entry beside [`locale`](#locale). | `headers` enables request routing, which disables the browser's HTTP cache and blocks service workers. #### `basicAuth` HTTP basic authentication. The browser answers a `401` challenge from the app's origin with these credentials. A challenge from any other origin goes unanswered unless [`credentialOrigins`](#credentialorigins) lists it. ```ts import { secrets } from 'e2e'; web({ basicAuth: { username: 'staging', password: secrets.get('staging-password') } }); ``` A `secrets.get(name)` password resolves when each attempt starts and is redacted like any configured secret. So is the base64 credential of the `Authorization` header it becomes. ```ts /** HTTP basic authentication the browser answers a `401` challenge from the app's origin with. */ export interface WebBasicAuth { /** The user name; `:` is not allowed in one (RFC 7617). */ readonly username: string; /** The password, or `secrets.get(name)` for one in `config.secrets`. */ readonly password: string | Secret; } ``` | Throws | When | | --- | --- | | `INVALID_CONFIG` | A `:` in the user name, or an unknown key. | WebKit can't scope a credential to an origin on its scheme's default port (`https://staging.example.com`) or with an IPv6 host. When the app's origin or one in `credentialOrigins` is such an origin, WebKit answers a `401` from any origin, as Playwright does by default. The secret protection is text only. A page that renders the password on screen is not masked in screenshots or model pixels ([Security rules](/reference/security#secrets-in-engine-options)). #### `credentialOrigins` More origins that receive [`headers`](#headers) and [`basicAuth`](#basicauth), beyond the app's own, such as an API on another host behind the same gate. ```ts web({ headers: { 'x-preview-token': process.env.PREVIEW_TOKEN ?? '' }, credentialOrigins: ['https://api.staging.example.com'], }); ``` List each origin exactly. A `*` in the host and port `0` match no request. | Throws | When | | --- | --- | | `INVALID_CONFIG` | No `headers` or `basicAuth`, an entry that is not an `http:` or `https:` origin with no path, query, or fragment, a `*` in the host, or port `0`. | #### `testIdAttribute` The attribute that carries an element's test id: what the `testId` query (`screen.getByTestId`) resolves and what `SemanticNode.testId` reports. ```ts web({ testIdAttribute: 'data-test' }); // default: 'data-testid' ``` #### `userAgent` The `User-Agent` every attempt's context sends and `navigator.userAgent` reports, for an app that switches into a test mode on a marker in the agent string. ```ts web({ userAgent: 'Mozilla/5.0 e2e' }); // default: the browser's own ``` #### `locale` The locale every attempt's context runs in, a BCP 47 tag: what `navigator.language`, `Intl` formatting, and the `Accept-Language` header report. ```ts web({ locale: 'de-DE' }); // default: the browser's own ``` #### `timezoneId` The IANA time zone every attempt's context runs in: what `Date` and `Intl` resolve local time against. ```ts web({ timezoneId: 'Europe/Berlin' }); // default: the machine's ``` #### Media emulation `web({ colorScheme, reducedMotion })` sets the media features every page of every attempt reports, as Playwright's context options of the same names do. `browser.emulateMedia(media)` changes them for one attempt. ```ts web({ colorScheme: 'dark', reducedMotion: 'reduce' }); // default: the browser's own await browser.emulateMedia({ colorScheme: 'light' }); ``` - The page's `@media` rules and `matchMedia` read them from the first paint. - A persistent context takes the options too: the engine sets them on each page it opens. - `emulateMedia` applies for the rest of the attempt, on every open tab and every tab opened after them, through `app.restart()` and `app.clearState()`. - It works before the first navigation, so the next `app.open` loads with them. - A feature it leaves out keeps its value. - A tab the app opens itself gets a test's change as it appears, on a persistent context too, so a script it runs at load may still read the configured values. ```ts /** User preferences a page reads through `@media` rules and `matchMedia`. */ export interface WebMedia { /** `prefers-color-scheme`. */ readonly colorScheme?: 'light' | 'dark' | 'no-preference'; /** `prefers-reduced-motion`. */ readonly reducedMotion?: 'reduce' | 'no-preference'; } ``` | Throws | When | | --- | --- | | `INVALID_CONFIG` | A feature or value outside `WebMedia`, in `web()`. | | `INVALID_ARGUMENT` | A feature or value outside `WebMedia`, in `emulateMedia`. | #### Init scripts An init script runs in every document before the page's own scripts, in every tab and frame. `web({ initScripts })` applies to every test; `browser.addInitScript` adds one for the rest of the test. ```ts await browser.addInitScript((value) => { Math.random = () => value; }, 0.5); await app.open('/raffle'); ``` - A function cannot close over test variables. Pass a JSON `arg` instead. - A script added after the page opened runs from the next navigation or reload. - `browser.addInitScript` takes the same three forms, or a function with its JSON `arg`. Its overloads are on [`Browser`](#browser-interface). ```ts /** JavaScript source, a file relative to the project root, or a function. */ export type WebInitScript = string | { readonly path: string } | (() => unknown); ``` ### The browser fixture `browser` is the whole browser, showing one active tab. - What reads or acts on a page acts on the active tab: `goto`, `reload`, `back`, `forward`, `url`, `title`, `waitForURL`, `locator`, `frameLocator`, `evaluate`, `evaluateOn`, `waitForResponse`, `waitForRequest`, `waitForDownload`, `keyboard`, `mouse`, the `expect(browser)` matchers, and every `screen` query. - What belongs to the browser covers every tab: `cookies`, `setCookies`, `clearCookies`, `route`, `unroute`, `unrouteAll`, `onDialog`, `addInitScript`, and [`clock`](#clock). - `setViewport` sizes the active tab and every tab opened after it. - [`emulateMedia`](#media-emulation) changes media on all open and future tabs. - [`setNetwork`](#setnetwork) takes every tab and service worker offline. - A tab the app opens, from a `target="_blank"` link or `window.open`, opens in the background: the active tab stays where it was until `waitForPopup` or `activate` makes another one active. See [Tabs](#tabs). - Every `browser` call is a recorded `browser.` step, except `locator` and `frameLocator`. They build a locator without touching the page, and the action or assertion on it is the step. - A relative URL resolves against the target's `app.url`, else `APP_URL_REQUIRED`. - Declare `platforms: ['web']` in a suite that also runs on other platforms. - `expect(browser)` returns the `BrowserExpectation` the engine attaches: `toHaveURL`, `toHaveTitle`, `toHaveClass`, `toHaveCSS`, and `toHaveJSProperty`. See [browser matchers](/reference/expect#browser-matchers). | Member | Returns | | --- | --- | | [`name`](#name-version) | `BrowserName` | | [`version`](#name-version) | `string` | | [`goto`](#goto) | `Promise` | | [`reload`](#reload-back-forward) | `Promise` | | [`back`](#reload-back-forward) | `Promise` | | [`forward`](#reload-back-forward) | `Promise` | | [`url`](#url-title) | `Promise` | | [`title`](#url-title) | `Promise` | | [`waitForURL`](#waitforurl) | `Promise` | | [`locator`](#locator) | `Locator` | | [`frameLocator`](#framelocator) | `FrameScreen` | | [`evaluate`](#evaluate) | `Promise` | | [`evaluateOn`](#evaluateon) | `Promise` | | [`addInitScript`](#init-scripts) | `Promise` | | [`route`](#route) | `Promise` | | [`unroute`](#unroute) | `Promise` | | [`unrouteAll`](#unrouteall) | `Promise` | | [`waitForResponse`](#waitforresponse) | `Promise` | | [`waitForRequest`](#waitforrequest) | `Promise` | | [`cookies`](#cookies) | `Promise` | | [`setCookies`](#setcookies) | `Promise` | | [`clearCookies`](#clearcookies) | `Promise` | | [`setViewport`](#setviewport) | `Promise` | | [`emulateMedia`](#media-emulation) | `Promise` | | [`setNetwork`](#setnetwork) | `Promise` | | [`onDialog`](#ondialog) | `Promise<() => Promise>` | | [`tabs`](#tabs) | `readonly BrowserTab[]` | | [`waitForPopup`](#tabs) | `Promise` | | [`newTab`](#tabs) | `Promise` | | [`waitForDownload`](#waitfordownload) | `Promise<{ path, absolutePath, … }>` | | [`waitForDownloads`](#waitfordownloads) | `Promise<{ path, absolutePath, … }[]>` | | [`keyboard`](#keyboard) | `{ press, down, up, type }` | | [`mouse`](#mouse) | `{ move, wheel, down, up }` | | [`webmcp`](#webmcp) | `{ tools, callTool }` | | [`clock`](#clock) | `BrowserClock` | The [config](/reference/config) sets each member's budget: - `goto`, `reload`, `back`, and `forward`: [`timeout`](/reference/config#timeout), the same budget `app.open()` uses. - `waitForURL`: [`assertionTimeout`](/reference/config#assertiontimeout). - Every other member: [`actionTimeout`](/reference/config#actiontimeout). `name`, `version`, `locator`, and `frameLocator` touch no page and take none. A `{ timeout }` option overrides the budget on `goto`, `reload`, `back`, `forward`, `waitForResponse`, `waitForRequest`, `waitForPopup`, `waitForDownload`, and `waitForDownloads`, capped by the test deadline (`cleanupTimeout` in `afterEach`); `0` waits until it. `url`, `title`, `evaluate`, `evaluateOn`, `addInitScript`, `route`, `unroute`, `unrouteAll`, `cookies`, `setCookies`, `clearCookies`, `setViewport`, `emulateMedia`, `setNetwork`, `onDialog`, `newTab`, the `BrowserTab` methods, `keyboard.*`, `mouse.*`, `webmcp.*`, and `clock.*` take no override. #### `name`, `version` The browser the test runs in, and the version that browser reports. ```ts test('exports a PDF', async ({ app, browser }) => { test.skip(browser.name !== 'chromium', 'PDF export is Chromium only'); console.log(browser.version); // 159.0.8154.6 await app.open('/invoice'); }); ``` - `name` is `'chromium'`, `'firefox'`, or `'webkit'`, the value of the [`browser`](#browser) option. - A browser attached with [`connect`](#connect) or leased from a provider is always `'chromium'`, because the engine drives it over CDP. That holds for Chrome and Edge, and for a CDP server that isn't Chromium, such as [Lightpanda](/integrations/lightpanda). - `version` is read from the running browser. For an attached or hosted one it is what its CDP endpoint reports. The [`userAgent`](#useragent) option doesn't change it. - Both are properties, not steps, and can be read before the first navigation. - For the operating system, use `process.platform` when the browser runs on the runner's machine. For a hosted browser, read `navigator.platform` with [`evaluate`](#evaluate). - To tell Chrome from Edge, read `navigator.userAgentData.brands` with [`evaluate`](#evaluate). Chromium exposes it only in a secure context: an HTTPS, loopback, or `file:` page. #### `goto` Navigates the active tab to a URL. ```ts await browser.goto('/dashboard', { waitUntil: 'networkidle' }); // default: 'load' ``` `waitUntil` is `'load'`, `'domcontentloaded'`, or `'networkidle'`. | Throws | When | | --- | --- | | `POLICY_DENIED` | A URL whose scheme is not `http:` or `https:`. `about:blank` is admitted. On a target whose [`app.url` is a file](/reference/config#a-file-as-the-app), a `file:` URL outside that file's directory, or of a directory. | | `APP_URL_REQUIRED` | A relative URL, on a target that declares no `app.url`. | | `ACTION_FAILED` | The navigation failed. | #### `reload`, `back`, `forward` `reload` reloads the current document. `back` and `forward` navigate browser history once. All three wait for the document load. A back/forward-cache restore can reuse an already-loaded document. Use locators and assertions to wait for app content. ```ts await browser.reload(); await browser.back({ timeout: 10_000 }); ``` | Throws | When | | --- | --- | | `ACTION_FAILED` | The navigation failed. | #### `url`, `title` Return the active tab's current URL and title. ```ts const url = await browser.url(); const title = await browser.title(); ``` #### `waitForURL` Waits for the current URL to match. It reads the URL at 0, 20, and 50 ms, then every 100 ms from the start, the same poll as `expect(browser).toHaveURL`. ```ts await browser.waitForURL('**/checkout'); await browser.waitForURL(/\/orders\/\d+$/, { timeout: 15_000 }); ``` - A string uses Playwright's URL glob grammar: `*` matches within one path segment, `**` across `/`, `{a,b}` matches either, and `\` escapes the next character. `?` is literal, so a query string reads as written, and a string with no wildcard matches that URL exactly. A glob resolves against the base URL unless it starts with `*` or is an absolute URL such as `https://x.test/**` or `about:blank`, and a resolved glob's scheme and host match in any letter case. Globs match non-ASCII text and spaces in paths and queries as the browser encodes them. In strings that use glob syntax, e2e also matches `"`, `<`, and `>` against their encoded forms in paths, queries, and fragments. The same applies to `` ` `` in paths and fragments, `^` and escaped `\{` and `\}` in paths, and `'` in special URL queries such as HTTP and HTTPS. The empty string matches any URL. - `expect(browser).toHaveURL` reads `*` and `{` as themselves, as Playwright's does; [`route`](#route), `unroute`, `waitForResponse`, and `waitForRequest` read the same globs as this wait. - A `RegExp` tests the full URL. | Throws | When | | --- | --- | | `INVALID_ARGUMENT` | A pattern that is not a string or `RegExp` (a predicate function, say), a glob that nests a `{` or leaves a `{` or `}` unmatched, or an option other than `timeout`, such as Playwright's `waitUntil`. | | `ASSERTION_FAILED` | The URL did not match before the timeout. | | `APP_URL_REQUIRED` | A relative pattern on a target with no `app.url`. | #### `locator` Creates a web-only locator from a Playwright selector. ```ts const conditions = browser.locator( '[data-testid="row"] >> nth=2 >> [data-testid="conditions"] > div', ); ``` - The selector is CSS by default, XPath with `xpath=` or a leading `//`, and takes `>>` chains, so the example scopes CSS to one row. - Use `filter({ has })` for an element that contains another. | Throws | When | | --- | --- | | `INVALID_LOCATOR` | An empty selector, or a `*` capture before the last part (`*css=article >> text=Hello`). | Every `screen` query searches its scope and each closed shadow root the page attached under it, with Playwright's own role, name, text, label, and attribute matching and each node found once. A control the observed tree lists inside a closed root resolves and takes actions and reads. `locator`, `frameLocator`, and `filter({ hasText })` keep Playwright's reach and stop at a closed root; the [browser guide](/browser#shadow-dom) has the details. #### `frameLocator` Creates a screen query scope inside one iframe. ```ts const payment = browser.frameLocator('#payment-frame'); await payment.getByLabel('Card number').fill('4242424242424242'); ``` It returns a `FrameScreen`, a `Screen` whose queries answer from inside the frame. Use the frame's `locator` only when the control has no accessible name, label, placeholder, or test id. The [browser guide](/browser#reach-into-an-iframe) shows when that applies. ```ts export interface FrameScreen extends Screen { /** Creates a web-only CSS or XPath locator inside this frame. */ locator(selector: string): Locator; /** Creates a screen query scope inside an iframe nested in this frame. */ frameLocator(selector: string): FrameScreen; } ``` The errors are the same at the page and inside a frame: | Throws | When | | --- | --- | | `INVALID_LOCATOR` | An empty selector, here or in the frame's `locator`. | | `LOCATOR_NOT_FOUND` | No frame matches. | | `LOCATOR_AMBIGUOUS` | Several frames match. | #### `evaluate` Evaluates trusted test code in the page and returns its result. ```ts const count = await browser.evaluate(() => document.querySelectorAll('li').length); const flag = await browser.evaluate( (name: string) => window.localStorage.getItem(name), 'featureFlags', ); const title = await browser.evaluate('document.title'); ``` - The function runs in the page and cannot access variables from the test. e2e serializes it by its source and inlines it into the page, so it must not close over anything outside its own body. Helpers declared inside the body work. Pass outside values through `arg`. - A string is evaluated as a single expression, not as statements. If it evaluates to a function, that function is called with `arg`; otherwise its value is the result. - A promise, from either, is awaited. | Throws | When | | --- | --- | | `INVALID_ARGUMENT` | `arg` or the return value is not a [`JsonValue`](#jsonvalue). A class instance, such as a `DOMRect` or an element, is not: return `rect.toJSON()` or the fields you need. | | `EVALUATE_FAILED` | The evaluated code threw, or the page replaced a JavaScript built-in such as `Map` that the engine needs. The error carries the message. | | `ACTION_FAILED` | A Playwright timeout. | | `ENGINE_FAILURE` | The page closed or the context was lost. | #### `evaluateOn` Evaluates trusted test code in the page on the one element a locator matches, and returns its result. ```ts const nav = screen.getByRole('navigation', { name: 'Main' }); const position = await browser.evaluateOn(nav, (el) => getComputedStyle(el).position); const width = await browser.evaluateOn( browser.frameLocator('iframe').locator('aside'), (el, extra: number) => (el as HTMLElement).offsetWidth + extra, 10, ); ``` - The locator resolves like a locator read: its scope, its frame, and exactly one match, waited for up to `actionTimeout`. A node the page replaces before the code runs resolves again. - The function is called with the element, then `arg`. The element exists only in the page, so the test never holds it. The rules for the function, a string, and the result are those of [`evaluate`](#evaluate). - It is meant for reads. The code can change the page, but act through the locator instead, so the step records the action. - The code runs once. A navigation while it runs fails the call with `ENGINE_FAILURE`, exit code 3, as it fails [`evaluate`](#evaluate), and the code is never run again on the new page. Playwright reports the same case as a test failure. - To wait for a value, use [`toHaveCSS`](/reference/expect#tohavecss) or [`toHaveJSProperty`](/reference/expect#tohavejsproperty). | Throws | When | | --- | --- | | `INVALID_LOCATOR` | The target is not an e2e locator, or belongs to another target or attempt. The message names `browser.evaluateOn`. | | `LOCATOR_NOT_FOUND` | Nothing matches within `actionTimeout`. | | `LOCATOR_AMBIGUOUS` | Two or more elements match. | | `POLICY_DENIED` | The element is a secure field, such as a password input. The code never runs. | | `INVALID_ARGUMENT` | `arg` or the return value is not a [`JsonValue`](#jsonvalue). | | `EVALUATE_FAILED` | The evaluated code threw, or the top-level page replaced a JavaScript built-in that the engine needs. The error carries the message. | | `ACTION_FAILED` | The code did not finish within `actionTimeout`. | | `ENGINE_FAILURE` | The page closed or the context was lost, or the page navigated while the code ran. | #### `route` Adds an attempt-scoped network route. ```ts await browser.route('**/api/quote', async (route) => { await route.fulfill({ json: { cents: 4200 } }); }); await browser.route({ method: 'POST', url: '**/api/orders' }, async (route) => { await route.fulfill({ json: { id: 7 } }); }); ``` `route.fetch()` returns the upstream `{ url, status, headers, body(), text(), json() }` with the configured headers when its origin gets them, under the action timeout, without deciding the route. It does not follow redirects, which could take it past the navigation rule. - The pattern is a string or a `RegExp`, read as [`waitForURL`](#waitforurl) reads one: a string is a glob in Playwright's grammar (`?` literal, `{a,b}` either) resolved against the base URL, so one with no wildcard is an exact URL. `unroute`, `waitForResponse`, and `waitForRequest` take the same patterns. - `{ method, url }` narrows the pattern to one HTTP method too. `method` is case-insensitive, `url` keeps the string or `RegExp` grammar above, and `unroute`, `waitForResponse`, and `waitForRequest` take the same form. - A route whose method does not match steps aside for the routes registered before it, then the network, as if its URL had not matched. - A method pattern matches that method exactly: a `GET` route does not answer `HEAD`. - A route survives `app.restart()`, `app.clearState()`, and session restore. - Routes run newest first. - The handler must decide exactly once, with `fulfill`, `continue`, `fallback`, or `abort`, each described on `WebRoute` below. - A `continue` URL goes through the same rule as `goto`. A `continue` header set to `undefined` is dropped, also on redirects. - A `fulfill` body is a string or bytes (`Buffer`, `Uint8Array`), sent as is. - To set several cookies, join them with `\n` in one `set-cookie` header, as `route.fetch()` headers report them. Any other line break in a header is refused. - A handler that throws (a failed `expect` on the request, say) fails the next step with that error, or the attempt at its end when no step follows. A step the handler made fail, such as the `goto` whose request it left aborted, fails with the handler's error. A `goto` whose request a handler aborted on purpose fails with `ACTION_FAILED`. A handler still running then gets the cleanup budget to finish. Whatever it throws after the budget is dropped. | Throws | When | | --- | --- | | `INVALID_ARGUMENT` | A pattern that is not a string, `RegExp`, or `{ method, url }`; a glob that nests a `{` or leaves a `{` or `}` unmatched; a `{ method, url }` pattern with a missing or extra key, a method that is not an HTTP method, or a `url` that is not a string or `RegExp`. Separately, an option a decision does not take (Playwright's `abort(errorCode)`, a misspelled key such as `bodyy`) aborts the request and fails the next step. | | `APP_URL_REQUIRED` | A relative pattern on a target with no `app.url`. | | `ACTION_FAILED` | The handler decided twice or not at all. | | `POLICY_DENIED` | A `continue` URL with a forbidden scheme. | | `CLEANUP_TIMEOUT` | A handler outlived the cleanup budget. It fails the attempt. | ```ts /** * One of `json`, `body`, or `path`, or none for an empty body. `path` names a * file relative to the project root; its `Content-Type` follows its * extension unless `contentType` or a `content-type` header sets one. */ export type RouteFulfillResponse = { status?: number; /** Response headers; `set-cookie` may join several cookies with `\n`, as `route.fetch()` reports them. */ headers?: Record; /** Sets the `Content-Type` response header. */ contentType?: string; } & ( | { json: JsonValue; body?: never; path?: never } | { body: string | Uint8Array; json?: never; path?: never } | { path: string; json?: never; body?: never } | { body?: never; json?: never; path?: never } ); /** What `continue` changes about the request before it goes to the network. */ export interface RouteContinueOverrides { /** Resolved against the base URL like `goto`; must keep the request's scheme. */ url?: string; /** Request method. */ method?: string; /** Replaces every request header; `undefined` drops one, and the configured `headers` for an allowed origin are added on top. */ headers?: Record; /** Request body. */ postData?: string; } /** A URL pattern narrowed to one HTTP method. */ export interface RouteMatcher { /** The HTTP method to match, case-insensitive: `'POST'` and `'post'` are the same. */ readonly method: string; /** * The URL pattern: a string using the same grammar as a plain `route` * pattern, or a `RegExp`. `route`, `waitForResponse`, and `waitForRequest` * match requests against it; `unroute` compares it structurally. */ readonly url: string | RegExp; } /** A request the page made: what a route handler reads as `route.request` and `waitForRequest` returns. */ export interface WebRequest { /** Request URL. */ readonly url: string; /** HTTP method, as the page sent it. */ readonly method: string; /** * Request headers, lower-cased names. The cookie headers the browser adds * on its own are there only when a route intercepts the request, so always * in `route.request`. */ readonly headers: Readonly>; /** Request body as text; absent when the request has none. */ readonly postData?: string; } export interface WebRoute { /** The intercepted request. */ readonly request: WebRequest; /** Reads upstream without deciding the route or following redirects. */ fetch(): Promise; /** Fulfills the intercepted request once. */ fulfill(response: RouteFulfillResponse): Promise; /** Sends the intercepted request to the network once, skipping every other route. */ continue(overrides?: RouteContinueOverrides): Promise; /** Hands the intercepted request to the route registered before this one, or the network when none matches. */ fallback(): Promise; /** Aborts the intercepted request once. */ abort(): Promise; } ``` #### `unroute` Removes the routes registered with the same pattern: the same string, the same `RegExp` source and flags, or the same method and URL. It compares patterns rather than matching URLs, so `unroute('**/api/*')` does not remove a route registered for `'**/api/orders'`. ```ts await browser.unroute('**/api/quote'); await browser.unroute({ method: 'POST', url: '**/api/orders' }); ``` | Throws | When | | --- | --- | | `INVALID_ARGUMENT` | A pattern that is not a string, `RegExp`, or `{ method, url }`; a `{ method, url }` pattern with a missing or extra key, a method that is not an HTTP method, or a `url` that is not a string or `RegExp`. | #### `unrouteAll` Removes every route registered by the browser fixture, preserving configured headers. ```ts await browser.unrouteAll(); ``` #### `waitForResponse` Waits for a response on the active tab matching a [`route`](#route) pattern or a predicate. ```ts const [created] = await Promise.all([ browser.waitForResponse({ method: 'POST', url: '**/api/orders' }), screen.getByRole('button', 'Place order').tap(), ]); expect(created.status).toBe(201); const [ready] = await Promise.all([ browser.waitForResponse( async (response) => response.url.endsWith('/api/jobs/42') && response.status === 200 && (await response.json<{ state: string }>()).state === 'done', { timeout: 15_000 }, // default: actionTimeout ), screen.getByRole('button', 'Run job').tap(), ]); expect(ready.request.method).toBe('GET'); ``` - Start the wait before the action that triggers the request, usually in `Promise.all`. It also works before the first `browser.goto` or `app.open`. - Pass a URL glob string, a `RegExp`, `{ method, url }`, or a predicate function. Patterns use the same rules as [`route`](#route). - A predicate runs once per response with a `PageResponse` and returns `boolean | Promise`. At runtime, any truthy value matches. Async predicates can run at the same time on several responses, and the first to match wins, as in Playwright. - If a predicate throws or rejects, the step fails with that error unchanged. An e2e error keeps its code, so a failed `expect` throws `ASSERTION_FAILED` and an unreadable body throws `ACTION_FAILED`. Any other throw fails with `ERROR`. - With a pattern, or a predicate that does not read the body, the wait resolves as soon as response headers arrive. - Inside a predicate, `body()`, `text()`, and `json()` share the wait's timeout. A body the page never finishes reading, such as a stream or an unclosed response, can hold the predicate until the timeout, as in Playwright. When the wait settles, e2e cancels body reads still pending on passed-over responses. - On the returned `PageResponse`, `body()`, `text()`, and `json()` each use `config.actionTimeout`, capped by the test deadline. - `url`, `status`, `headers`, and `request` are properties, not methods, and are always readable without waiting for the body. Only `body()`, `text()`, and `json()` are methods. - On an empty body, `body()` returns an empty `Buffer`, `text()` returns `''`, and `json()` rejects. - Traces label the step with the pattern, or `predicate` for a function. | Throws | When | | --- | --- | | `INVALID_ARGUMENT` | A pattern that is not a string, `RegExp`, `{ method, url }`, or function; a glob that nests a `{` or leaves a `{` or `}` unmatched; a `{ method, url }` pattern with a missing or extra key, a method that is not an HTTP method, or a `url` that is not a string or `RegExp`; an option other than `timeout`, such as Playwright's `signal`. | | `APP_URL_REQUIRED` | A relative pattern on a target with no `app.url`. | | `ACTION_FAILED` | No response matches before the timeout. From `body()`, `text()`, or `json()`: a body that does not finish within their budget, or a body the browser cannot read, such as a connection cut short of `Content-Length`, an aborted request, or a redirect whose body the browser never keeps, instead of returning an empty string. | ```ts /** * An HTTP response: what `request` calls, the web engine's * `browser.waitForResponse`, and `route.fetch()` return. */ export interface WebResponse { /** Response URL. */ readonly url: string; /** HTTP status. */ readonly status: number; /** Response headers, lower-cased names; `request` and `route.fetch()` join several `set-cookie` values with `\n`, `waitForResponse` leaves cookie headers out. */ readonly headers: Readonly>; /** Waits for the body and returns its bytes; rejects with `ACTION_FAILED` when the body could not be read. */ body(): Promise; /** Waits for the body and parses it as JSON; rejects with `ACTION_FAILED` when the body could not be read. */ json(): Promise; /** Waits for the body and reads it as text; rejects with `ACTION_FAILED` when the body could not be read. */ text(): Promise; } /** What `waitForResponse` returns and its predicate reads: a `WebResponse` and the request it answers. */ export interface PageResponse extends WebResponse { /** The request this response answers. */ readonly request: WebRequest; } ``` #### `waitForRequest` Waits for a request on the active tab matching a [`route`](#route) pattern or a predicate. It resolves when the page sends the request, before any response arrives. ```ts const [order] = await Promise.all([ browser.waitForRequest({ method: 'POST', url: '**/api/orders' }), screen.getByRole('button', 'Place order').tap(), ]); expect(JSON.parse(order.postData ?? '{}')).toEqual({ sku: 'A-1', quantity: 2 }); const [search] = await Promise.all([ browser.waitForRequest( (request) => new URL(request.url).searchParams.get('q') === 'shoes', { timeout: 10_000 }, // default: actionTimeout ), screen.getByRole('searchbox').fill('shoes'), ]); expect(search.method).toBe('GET'); ``` - Start the wait before the action that triggers the request, usually in `Promise.all`. It also works before the first `browser.goto` or `app.open`. - Returns a [`WebRequest`](#route), the same type as `route.request`: `url`, `method`, `headers`, and optional `postData`. Every field is a property. `headers` has lower-cased names. The cookie headers the browser adds on its own are there only when a [`route`](#route) intercepts the request. - A predicate runs once per request with a `WebRequest`. Truthy matching, concurrent async predicates, thrown errors, and the `predicate` trace label work the same way as in [`waitForResponse`](#waitforresponse). | Throws | When | | --- | --- | | `INVALID_ARGUMENT` | Any pattern shape or option [`waitForResponse`](#waitforresponse) refuses, including any option other than `timeout`. | | `APP_URL_REQUIRED` | A relative pattern on a target with no `app.url`. | | `ACTION_FAILED` | No request matches before the timeout. | #### `cookies` Returns every cookie of the browser, or only the cookies a request to a URL would carry. ```ts const all = await browser.cookies(); const sent = await browser.cookies('/api/orders'); const either = await browser.cookies(['/api/orders', 'https://auth.example.com']); ``` - A cookie matches a URL by its domain, its path, and `Secure`: a `Secure` cookie matches `https` URLs, and `http` ones on a loopback host such as `localhost`. - A relative URL resolves against the base URL, as `goto` resolves it. - An empty list returns no cookies. | Throws | When | | --- | --- | | `INVALID_ARGUMENT` | A value that is not a string or an array of strings. | | `POLICY_DENIED` | An unparseable URL or one that is not `http(s)`. | | `APP_URL_REQUIRED` | A URL, on a target that declares no `app.url`. | #### `setCookies` Validates every cookie, then sets them. ```ts await browser.setCookies([{ url: 'http://localhost:3000', name: 'tz', value: 'UTC' }]); ``` - A relative `url` resolves against the base URL, as `goto` resolves it. - For the `domain` form the scheme follows the base URL, and a leading `.` is stripped. | Throws | When | | --- | --- | | `INVALID_ARGUMENT` | Not an array, or a cookie the `Cookie` type does not allow (a wrong field type, neither or both of `url` and `domain`/`path`, a `domain` that is not a bare host, an `expires` that is not in seconds, an unknown key). Nothing is set. | | `POLICY_DENIED` | An unparseable target or a forbidden scheme. Nothing is set. | ```ts export interface CookieFields { /** Cookie name. */ name: string; /** Cookie value. */ value: string; /** Unix timestamp in whole seconds. */ expires?: number; /** HttpOnly flag. */ httpOnly?: boolean; /** Secure flag. */ secure?: boolean; /** SameSite attribute. */ sameSite?: 'Strict' | 'Lax' | 'None'; } /** `url`, or `domain` with an optional `path`, never both. */ export type Cookie = CookieFields & ( | { url: string; domain?: never; path?: never } | { url?: never; domain: string; path?: string } ); ``` #### `clearCookies` `clearCookies({ name?, domain?, path? })` removes cookies matching every filter given. Strings match exactly; RegExp matches the field. With no options it removes every cookie. Other storage stays. ```ts await browser.clearCookies({ name: /^session/, path: '/' }); ``` ```ts export interface CookieFilter { name?: string | RegExp; domain?: string | RegExp; path?: string | RegExp; } ``` #### `setViewport` Sets the viewport size and records the new size on the report. ```ts await browser.setViewport({ width: 390, height: 844 }); await app.open('/'); ``` - It works before the first navigation too, as Playwright's `setViewportSize` does. The next `app.open` loads at that size, so a phone-sized test never renders the desktop layout first. - The size holds for the rest of the attempt, through `app.restart()` and `app.clearState()`. #### `setNetwork` Takes the browser offline, or back online, for the rest of the attempt. ```ts await app.open('/'); await browser.setNetwork('offline'); await screen.getByRole('button', 'Refresh').tap(); await expect(screen.getByText('You are offline')).toBeVisible(); await browser.setNetwork('online'); ``` - Offline, a request that reaches the network fails as it does with no connection, and `navigator.onLine` is `false`. The open page gets an `offline` event. - It covers every tab, every tab opened after, and the page's service workers. A worker can still answer from its cache, so `browser.reload()` loads a page it cached. - The browser's HTTP cache still answers too. Chromium serves a response that is still fresh, Firefox any response it stored, and WebKit none. A navigation to a page no cache holds fails. - A connection that is already open, such as an event stream, stays open. - After a navigation fails, Chromium shows its own error page, and a `reload()` of that page resolves. Assert on the screen. - It holds through `app.restart()` and `app.clearState()`. Every attempt starts online, a retry too. - It works before the first navigation. - Chromium and WebKit still fulfill a request a [`route`](#route) answers. Firefox fails it. - With [`headers`](#headers) configured, service workers are blocked, so no worker serves a cached page. - The [`request`](/reference/request) fixture runs in the runner's process and stays online. | Throws | When | | --- | --- | | `INVALID_ARGUMENT` | A state other than `'online'` or `'offline'`. | | `ACTION_FAILED` | A navigation fails while the browser is offline. | #### `onDialog` Registers an attempt-scoped handler for native dialogs and returns an unsubscribe function. ```ts const off = await browser.onDialog('accept'); await screen.getByRole('button', 'Delete').tap(); await off(); ``` - The handler is `'accept'`, `'dismiss'`, or a function that receives the `Dialog`. - A function handler must call `accept` or `dismiss`. One that does neither has the dialog dismissed, as an unhandled dialog does. - A handler that throws fails the next step with its error, or the attempt at its end when no step follows. One that throws before answering has its dialog dismissed. The errors surface on the next step, not on `onDialog`: | Throws | When | | --- | --- | | `APP_NOT_OPEN` | A function handler answered neither way, or no handler took the dialog. | | `ASSERTION_FAILED` | The handler's `expect` failed. | | `ENGINE_FAILURE` | The handler threw an unclassified error. | ```ts /** A native dialog as a test's handler sees it. */ export interface Dialog { /** The native dialog kind, independent of its message. */ readonly type: 'alert' | 'confirm' | 'prompt' | 'beforeunload'; /** The dialog's text. */ readonly message: string; /** Accepts the dialog once. */ accept(text?: string): Promise; /** Dismisses the dialog once. */ dismiss(): Promise; } export type DialogHandler = 'accept' | 'dismiss' | ((dialog: Dialog) => void | Promise); ``` #### Tabs A tab the app opens, from a `target="_blank"` link or `window.open`, opens in the background. The active tab stays where it was, and `screen`, `expect`, and the `browser` page methods keep acting on it. `waitForPopup` makes the tab its trigger opens active. When the active tab closes, the tab that opened it is active again, or the open tab that was active most recently when the opener is gone too. ```ts const popup = await browser.waitForPopup(() => screen.getByRole('button', 'Open verification tab').tap(), ); const code = await screen.getByText(/^TAB-/).textContent(); await popup.close(); // the opener is active again await screen.getByRole('textbox', 'Verification code').fill(code); ``` - `waitForPopup(trigger)` runs the trigger and resolves with the tab it opens once that tab is active. It takes the first tab the app opens after the wait starts, which can be one an earlier action opened whose page loaded only now. - `tabs()` returns the open tabs in the order they opened, the same `BrowserTab` for a tab the whole attempt. A tab joins once its first page loads, so two tabs one action opens are listed in the order their pages load. A tab that never gets a page is never listed: a `target="_blank"` link to a download, to a `mailto:` address, or to a response with no content. - `tab.activate()` makes a tab active without closing the others. `tab.close()` closes it, and when it was active, waits until the next one is. - `newTab()` opens a blank tab in the same browser context, with the same cookies and storage, and makes it active. Navigate it with `goto`. - A tab whose opener closed before the tab loaded is listed too, on Chromium. A page a test opens through `surfaceOf(engine)` is not. - The screencast records the active tab, one video segment per change. A tab that closes itself keeps no segment, since its page closes before the recording can be saved. A provider's own recording covers every tab. ```ts /** One tab of the browser the attempt drives. */ export interface BrowserTab { url(): Promise; title(): Promise; /** Whether this is the active tab. */ isActive(): boolean; isClosed(): boolean; /** Makes this the active tab. */ activate(): Promise; /** Closes the tab; the tab that opened it becomes active when it was. */ close(): Promise; } ``` | Throws | When | | --- | --- | | `ACTION_FAILED` | `waitForPopup`: no tab opened in time. A trigger that resolved in time fails with `no tab opened within ms; the trigger resolved after ms`, or with `the tab the app opened did not load within ms` when a tab was still loading its first page. `activate`: the tab has closed. | #### `waitForDownload` Runs a trigger and waits for the download it starts. ```ts const file = await browser.waitForDownload(() => screen.getByRole('link', 'Export CSV').tap(), ); ``` - It registers the file as a `download` artifact and returns its relative `path`, the runner-side `absolutePath`, and `suggestedFilename`. - Use `absolutePath` with file APIs to inspect the contents, including on a hosted browser. - On a hosted browser the file comes back through the provider's [`downloads`](/browser#downloads-on-the-provider). - The wait includes the trigger's own time. | Throws | When | | --- | --- | | `ACTION_FAILED` | The download did not complete in time. A trigger that resolved in time but started no download fails with `no download started within ms; the trigger resolved after ms`. | A trigger still running at the timeout fails with the step timeout. One that throws fails with its own error. #### `waitForDownloads` `waitForDownloads(trigger, { count })` calls the trigger once and returns `count` files in start order, each its own artifact, under the same timeout. When fewer start in time, the error names both counts; extra downloads are ignored. #### `keyboard` Viewport-level keyboard input, for whatever has focus. ```ts await browser.keyboard.press('Escape'); await browser.keyboard.type('hello'); ``` - `type(text)` types plain text only, never a `Secret`. - Prefer `locator.press` and `locator.fill` when a target exists. - [`Browser`](#browser-interface) describes each method. #### `mouse` Viewport-level pointer input from test code, independent of agent observations. ```ts await browser.mouse.move(120, 240); await browser.mouse.down(); await browser.mouse.move(320, 240); await browser.mouse.up(); ``` [`Browser`](#browser-interface) describes each method, `wheel` included. #### WebMCP [WebMCP](https://github.com/webmachinelearning/webmcp) is an experimental browser API a page registers tools through, on `document.modelContext` (`navigator.modelContext` in Firefox). `browser.webmcp` lists the tools the page in the active tab registered and calls them from test code, with no model involved. ```ts title="e2e.config.ts" import type { E2EConfig } from 'e2e'; import { web } from '@e2e-dev/web'; export default { targets: [{ engine: web({ webmcp: true }), app: { url: 'http://localhost:3000' } }], } satisfies E2EConfig; ``` ```ts const tools = await browser.webmcp.tools(); expect(tools.map((tool) => tool.name)).toContain('add'); const result = await browser.webmcp.callTool('add', { a: 2, b: 40 }); expect(result).toEqual({ content: [{ type: 'text', text: '42' }] }); ``` - `web({ webmcp: true })` launches Chromium with `--enable-features=WebMCP`, or Firefox with its `dom.modelcontext` preferences. It is off by default, since with it every page sees an API most browsers do not have yet. WebKit has no WebMCP. The option is only for a browser the engine launches: start a browser reached through [`connect`](#connect) or a provider with that argument yourself. - The page has to be a secure context, `https:` or `localhost`, or it has no `document.modelContext` and both calls fail with `UNSUPPORTED_CAPABILITY`. The engine asks the page itself, so a browser reached through `connect` or a provider that was started without WebMCP fails the same way. - `tools()` returns the tools registered now, each with its `name`, `description`, `inputSchema`, and `annotations` when the page gave them. A page that registers none gives an empty list. The order is the browser's own and differs between Chromium and Firefox. - `callTool(name, input)` resolves with what the tool's `execute` resolved to, usually an object with a `content` array. `input` is a JSON object; left out or `null`, the tool gets an empty object. A result with `isError: true` comes back as it is, and a tool that resolves with nothing gives `null`. - An object or array comes back as its JSON, the same in Chromium and Firefox: a property left `undefined` is not in it, and a `Date` inside is a string. A tool that resolves with any other value gives its text, parsed when the text is JSON: `'42'` and `42` both give `42`, and a number past 2^53 loses digits. An empty string gives `'Operation succeeded'` in Chromium. Resolve with an object to keep the value as it is. - A tool that sends the page to another URL ends the call before it answers. The call fails with `ACTION_FAILED` once the new page has loaded, and the message says the tool may have run. A tool still running when the time runs out fails the same way. - Both cover the main frame of the active tab, not the frames inside it. - Names, descriptions, schemas, and results come from the page, so treat them as untrusted input. ```ts /** A tool a page registered through WebMCP, as the page describes it. */ export interface WebMcpTool { readonly name: string; readonly description: string; /** JSON Schema of the tool's input, when the page gave one. */ readonly inputSchema?: JsonValue; /** Hints the page gives about the tool. */ readonly annotations?: { /** The tool changes no state. */ readonly readOnly?: boolean; /** The tool's output may carry third-party content. */ readonly untrustedContent?: boolean; /** The tool takes a consequential action, such as placing an order. */ readonly consequential?: boolean; }; } ``` | Throws | When | | --- | --- | | `UNSUPPORTED_CAPABILITY` | The page has no WebMCP: the browser runs without it, or the page is not a secure context. The message says which, and how to fix it. | | `ACTION_FAILED` | `callTool`: the page registers no tool of that name (the message lists the ones it does), the tool threw or resolved with something JSON cannot hold (a `BigInt` inside, a cycle), or the call ended before the tool answered, because the page navigated or the time ran out. | | `INVALID_ARGUMENT` | `callTool`: `name` is not a non-empty string, or `input` is not a JSON object. | | `INVALID_CONFIG` | `web({ webmcp: true })` with `connect`, a browser provider, or WebKit. | #### `clock` `browser.clock` controls time in the attempt's pages: `Date`, `performance`, timers, `requestAnimationFrame`, and `requestIdleCallback`. It is Playwright's `page.clock`, with the same methods and arguments. ```ts await browser.clock.install({ time: new Date('2024-02-02T08:00:00Z') }); await browser.clock.pauseAt(new Date('2024-02-02T09:00:00Z')); await app.open('/offer'); await browser.clock.runFor(3000); // fires every timer due in 3 seconds await browser.clock.fastForward('30:00'); // jumps 30 minutes, firing each due timer once ``` | Method | What it does | | --- | --- | | `install({ time? })` | Fakes the time functions, starting at `time` (default: now). The clock runs on in real time. | | `pauseAt(time)` | Fast-forwards to `time` and stops there. Timers fire only through `runFor` and `fastForward`. | | `resume()` | Lets a paused clock run on in real time. | | `runFor(ticks)` | Advances the clock, firing every timer due on the way. | | `fastForward(ticks)` | Jumps ahead, firing each due timer at most once. | | `setFixedTime(time)` | Holds `Date.now()` and `new Date()` at `time`. Timers keep running. | | `setSystemTime(time)` | Changes the wall time without firing a timer. | - A `time` is epoch milliseconds, a string `new Date()` parses in the runner's process, or a `Date`. `ticks` are milliseconds, or `'ss'`, `'mm:ss'`, or `'hh:mm:ss'`. - Every other method installs the clock first if it isn't, as Playwright does: it starts at the Unix epoch, 1970-01-01, so call `install({ time })` first unless the next call sets the time. Install before `app.open` so the page loads on it; a page already open gets the clock at once. - The clock covers every tab and frame, the ones the app opens included. It holds through navigation, `app.restart()`, and `app.clearState()`, and ends with the attempt. - `app.clearState()` and session restore replay the clock's calls on the new context, as a new document does: a call that failed, such as a `runFor` whose timer threw, counts, and a refused `pauseAt` does not. A paused or fixed clock comes back as it was. A running one loses the real time that passed before the clear. - Only the page's time moves. The test's timeouts, `expect` polling, and the agent's waits keep real time, so a paused clock never holds a step. - A [CDP recovery](#recovering-a-cdp-transport) after the attempt used the clock fails the attempt with `ENGINE_FAILURE`: the open pages keep their clock but the reconnected browser cannot restore it. - A timer loop that never finishes, such as a 1 ms interval under `runFor('10:00:00')`, stops the call at `actionTimeout` with `ACTION_FAILED`. ```ts /** A point in time: epoch milliseconds, a string `Date` parses, or a `Date`. */ export type ClockTime = number | string | Date; /** A span of time: milliseconds, or a `'ss'`, `'mm:ss'`, or `'hh:mm:ss'` string. */ export type ClockTicks = number | string; export interface BrowserClock { install(options?: { time?: ClockTime }): Promise; fastForward(ticks: ClockTicks): Promise; runFor(ticks: ClockTicks): Promise; pauseAt(time: ClockTime): Promise; resume(): Promise; setFixedTime(time: ClockTime): Promise; setSystemTime(time: ClockTime): Promise; } ``` | Throws | When | | --- | --- | | `INVALID_ARGUMENT` | A time that is not a finite number, a parsable non-empty string, or a valid `Date`; ticks that are negative or outside `'hh:mm:ss'`; an unknown `install` option; `pauseAt` before the clock's current time. | | `EVALUATE_FAILED` | A timer the page ran during `runFor`, `fastForward`, or `pauseAt` threw. The message carries the page's error. | | `ACTION_FAILED` | The call ran past `actionTimeout`. | ## Installing browsers The package pins `playwright-core` to an exact version, so the engine always runs the Playwright it was tested against. An app that depends on Playwright itself keeps its own copy. The two share a browser cache only when their versions match. A missing browser downloads once per run, before the run's clock starts. To install browsers as their own step, in CI or a container image, run the package's command. It installs the browsers for the engine's pinned Playwright: ```bash npm npx @e2e-dev/web install chromium --with-deps ``` ```bash pnpm pnpm exec e2e-web install chromium --with-deps ``` ```bash bun bunx @e2e-dev/web install chromium --with-deps ``` - Name any of `chromium`, `firefox`, and `webkit`. With none named it installs `chromium`. - `--with-deps` also installs the system libraries the browsers need on Linux. When chromium or firefox is installed without them, [`e2e doctor`](/reference/cli#e2e-doctor) fails its `browser` check and a run's launch fails; both messages name the missing libraries and this command. - The command exits with the installer's exit code. ## Semantic capture recovery When the semantic reader times out, agent observations can recover with a fresh viewport screenshot. - Playwright runs a new secure-field mask sweep across every reachable frame, including open and closed shadow roots. Every mask probe must succeed. - The observation reports unavailable semantics and clears earlier node references. - Recovery requires time left in the operation budget and permission from the runner. `act` permits it; judgments require `vision: true` or `'only'`. - Failed masking, cancellation, and hard engine errors still stop the observation. When fallback is permitted, the reader reserves one quarter of the remaining observation budget, capped at two seconds, for the screenshot. The deadline covers the page walk, metadata and element readback, and nested frames. Semantic metadata crosses the Playwright connection as one JSON string, to cut serialization overhead. The elements the reader walked stay in one in-page array per document, and an action makes the handle for its node from that array the first time it reaches for it. A reference still names the element the walk read, not whatever sits at that position later. A page that replaces `JSON.stringify`, or adds `toJSON` methods to object or array prototypes, gets structured transfer. Cleanup does not wait for stalled protocol replies. An abandoned reader cannot reuse node IDs or publish references over a newer observation. ## surfaceOf Returns the live Playwright surface of a `web()` handle, for a [custom executor](/executors#driving-the-page-yourself) that drives the page itself. ```ts import { web, surfaceOf } from '@e2e-dev/web'; const engine = web(); const live = surfaceOf(engine); // PlaywrightLiveSurface | undefined live!.page(); // the Page of the current attempt live!.context(); // its BrowserContext ``` - It returns `undefined` for a handle from another package. - Direct Playwright calls are not recorded as steps. - After [CDP recovery](#recovering-a-cdp-transport), read the accessors again. | Throws | When | | --- | --- | | `INVALID_STATE` | An accessor called outside an active attempt, or on a handle that has not started in this process, such as a second `web()`. | ## Types The package exports these types for typing config helpers and fixtures: `WebEngine`, `WebOptions`, `WebMedia`, `WebScreencastOptions`, `WebConnectOptions`, `WebBasicAuth`, `WebInitScript`, `BrowserName`, `BrowserProvider`, `BrowserProviderScope`, `BrowserRequest`, `BrowserLease`, `BrowserReleaseContext`, `BrowserProviderDownloads`, `BrowserDownloadContext`, `PlaywrightLiveSurface`, `Browser`, `FrameScreen`, `BrowserExpectation`, `BrowserClock`, `ClockTime`, `ClockTicks`, `WebRoute`, `RouteFulfillResponse`, `RouteContinueOverrides`, `RouteMatcher`, `WebRequest`, `WebResponse`, `PageResponse`, `Cookie`, `CookieFields`, `CookieFilter`, `Dialog`, and `DialogHandler`. The runtime exports are `web`, [`surfaceOf`](#surfaceof), and `test`, `describe`, `beforeEach`, `afterEach`, `beforeAll`, and `afterAll`, typed with the `browser` fixture. ### `WebOptions` ```ts /** * Options of the browser engine: how it drives the app. The app itself * (its `url`, `environment`, `identity`, and the command that starts it) is * the target's `app`. */ export interface WebOptions { /** * Browser to launch, `chromium` by default. A `BrowserProvider` leases * hosted browsers instead: one per worker slot at `prepare`, or one per * attempt, each attached to over CDP and released when its scope ends. A * provider implies chromium and excludes `connect`. */ readonly browser?: BrowserName | BrowserProvider; /** * Whether a locally launched Chromium runs with its OS sandbox on; default * `true` on macOS and Windows, `false` on Linux. */ readonly chromiumSandbox?: boolean; /** * Initial viewport of every attempt's page; default 1280 by 720. `null` * emulates no size: the page fills the browser window, whatever size the * window has (a hosted browser's live view, a headed run), and * `browser.setViewport` still fixes one for the rest of the attempt. */ readonly viewport?: ViewportSize | null; /** * Device pixels per CSS pixel on every attempt's page, as * `window.devicePixelRatio` reads it; default 1. At 2 the page renders as * on a high-density display, and every saved screenshot * (`app.screenshot()`, a failure's, an `agent.assert`'s) is twice the * viewport's size on each side. The factor does not change the image the * model reads or the one `toHaveScreenshot` compares. It needs a viewport * size, so `viewport: null` refuses it, and a persistent context * (`connect.reconnectEndpoint`, or a provider with `scope: 'attempt'`) * refuses it. */ readonly deviceScaleFactor?: number; /** * How the engine's own screencast records an attempt that records video. * A browser provider that records (`BrowserProvider.record`) records in * its place, and ignores these. Which attempts record is the config's * `video`, not an engine option. */ readonly screencast?: WebScreencastOptions; /** * Attach to a remote browser over CDP instead of launching locally. Requires * the chromium browser (the default). Wired by a hosted-browser engine. */ readonly connect?: WebConnectOptions; /** * Headers added to every request that starts at the app's origin (the * scheme, host, and port of `app.url`) or one in `credentialOrigins`. * Useful for preview-protection tokens. A request that starts at another * origin goes without them; a redirect keeps them, to any origin. * Names are case-insensitive and replace existing headers of the same name. * This enables request routing, disables the browser's HTTP cache, and * blocks service workers. */ readonly headers?: Readonly>; /** * HTTP basic authentication. The browser answers a `401` challenge from the * app's origin, or one in `credentialOrigins`, with these credentials. */ readonly basicAuth?: WebBasicAuth; /** * More origins that receive `headers` and `basicAuth`, such as * `https://api.example.com`; requires `headers` or `basicAuth`. */ readonly credentialOrigins?: readonly string[]; /** * The attribute that carries an element's test id: what the `testId` query * (`screen.getByTestId`) resolves and what `SemanticNode.testId` reports. * Defaults to `data-testid`. */ readonly testIdAttribute?: string; /** * The `User-Agent` every attempt's context sends and `navigator.userAgent` * reports, for an app that switches into a test mode on a marker in the * agent string. Defaults to the browser's own. A `user-agent` entry in * `headers` beside it is `INVALID_CONFIG`, and so is a persistent context * (`connect.reconnectEndpoint`, or a provider with `scope: 'attempt'`). */ readonly userAgent?: string; /** * The locale every attempt's context runs in, a BCP 47 tag such as * `de-DE`: what `navigator.language`, `Intl` formatting, and the * `Accept-Language` header report. Defaults to the browser's own. An * `accept-language` entry in `headers` beside it is `INVALID_CONFIG`, and * so is a persistent context. */ readonly locale?: string; /** * The IANA time zone every attempt's context runs in, such as * `Europe/Berlin`: what `Date` and `Intl` resolve local time against. * Defaults to the machine's. A persistent context is `INVALID_CONFIG`. */ readonly timezoneId?: string; /** The `prefers-color-scheme` every page reports. See [Media emulation](#media-emulation). */ readonly colorScheme?: WebMedia['colorScheme']; /** The `prefers-reduced-motion` every page reports. See [Media emulation](#media-emulation). */ readonly reducedMotion?: WebMedia['reducedMotion']; /** Scripts every document runs before the page's own. See [Init scripts](#init-scripts). */ readonly initScripts?: readonly WebInitScript[]; /** Launches Chromium or Firefox with WebMCP, for `browser.webmcp`. See [WebMCP](#webmcp). */ readonly webmcp?: boolean; } ``` ### `Browser` interface ```ts /** * The browser the attempt drives, showing one active tab. Navigation, reads, * `locator`, `frameLocator`, `evaluate`, `waitForResponse`, `waitForRequest`, * `waitForDownload`, the keyboard and mouse, `expect(browser)`, and `screen` act on the active * tab; cookies, routes, and dialog handlers cover the whole browser, every * tab included. A tab the app opens (a `target="_blank"` link, * `window.open`) joins `tabs()` but does not become active on its own: * `waitForPopup` makes the tab its trigger opens active, and `activate` * any other. When the active tab closes, the tab that opened it is active * again. */ export interface Browser extends Expectable { /** * The browser the attempt drives, as the driver names it: the * `web({ browser })` value, and `chromium` for every browser the engine * attaches to over CDP (`connect`, a provider), whatever it is. */ readonly name: BrowserName; /** * The version the running browser reports, such as `159.0.8154.6`: for * an attached or hosted one, what its CDP endpoint reports. The target's * `userAgent` does not change it. */ readonly version: string; /** Navigates to an allowed URL. */ goto( url: string, options?: { waitUntil?: 'load' | 'domcontentloaded' | 'networkidle'; timeout?: number; }, ): Promise; /** Reloads the current document. */ reload(options?: ActionOptions): Promise; /** Navigates browser history back once. */ back(options?: ActionOptions): Promise; /** Navigates browser history forward once. */ forward(options?: ActionOptions): Promise; /** Returns the current URL. */ url(): Promise; /** Returns the current title. */ title(): Promise; /** Waits for the current URL to match. */ waitForURL(url: string | RegExp, options?: { timeout?: number }): Promise; /** Creates a web-only CSS or XPath locator. */ locator(selector: string): Locator; /** Creates a screen query scope inside one iframe. */ frameLocator(selector: string): FrameScreen; /** Evaluates trusted test code in the page: a function, or a string expression whose value is returned, called first if it is a function. */ evaluate(fn: string | (() => T | Promise)): Promise; /** Evaluates trusted test code with one required JSON-safe argument. */ evaluate( fn: string | ((arg: Arg) => T | Promise), arg: Arg, ): Promise; /** * Evaluates trusted test code in the page on the one element `target` * matches, with the locator's scope, strictness, and frame, waiting for it * like a read. The element is passed inside the page only; the result is * JSON. Meant for reads: the code can change the page, but a test should * act through the locator instead. The code runs once: a navigation while * it runs fails the call with `ENGINE_FAILURE`. A secure field is * `POLICY_DENIED`, as the locator getters deny it. */ evaluateOn( target: Locator, fn: string | ((element: Element) => T | Promise), ): Promise; /** * Evaluates trusted test code on the one element `target` matches, with * one required JSON-safe argument. */ evaluateOn( target: Locator, fn: string | ((element: Element, arg: Arg) => T | Promise), arg: Arg, ): Promise; /** Adds a script every document runs before the page's own, from the next navigation on. */ addInitScript(script: string | { path: string } | (() => unknown)): Promise; /** Adds an init script function called with one JSON argument. */ addInitScript(script: (arg: Arg) => unknown, arg: Arg): Promise; /** Adds an attempt-scoped network route, optionally narrowed to one HTTP method. */ route( pattern: string | RegExp | RouteMatcher, handler: (route: WebRoute) => void | Promise, ): Promise; /** * Removes the routes registered with the same pattern: the same string or * `RegExp` source and flags, and the same method for a `{ method, url }` * pattern. It does not URL-match registered routes. */ unroute(pattern: string | RegExp | RouteMatcher): Promise; /** Removes all routes registered by this browser fixture, preserving the configured headers. */ unrouteAll(): Promise; /** * Waits for a response on the active tab matching a URL pattern, a * `{ method, url }` matcher, or a predicate. The predicate runs per response * until one returns or resolves to a truthy value; throwing fails the wait * with the predicate's own error. */ waitForResponse( pattern: string | RegExp | RouteMatcher | ((response: PageResponse) => boolean | Promise), options?: { timeout?: number }, ): Promise; /** * Waits for a request on the active tab matching a URL pattern, a * `{ method, url }` matcher, or a predicate, and resolves when the page sends * it before any response arrives. Predicate matching and errors work the * same way as in `waitForResponse`. */ waitForRequest( pattern: string | RegExp | RouteMatcher | ((request: WebRequest) => boolean | Promise), options?: { timeout?: number }, ): Promise; /** * Returns every cookie of the browser, or only those a request to `urls` * (one URL or several) would carry. A relative URL resolves against the * base URL. */ cookies(urls?: string | readonly string[]): Promise; /** Sets cookies after URL validation. */ setCookies(cookies: readonly Cookie[]): Promise; /** Removes matching cookies only; without filters removes every cookie, preserving other storage. */ clearCookies(options?: CookieFilter): Promise; /** Sets the viewport size. */ setViewport(size: { width: number; height: number }): Promise; /** Emulates CSS media features on every open tab and every tab opened after them. */ emulateMedia(media: WebMedia): Promise; /** Takes the browser offline or back online for the rest of the attempt: every tab and the page's service workers. */ setNetwork(state: 'online' | 'offline'): Promise; /** Registers an attempt-scoped dialog handler and returns an unsubscribe function. */ onDialog(handler: DialogHandler): Promise<() => Promise>; /** Returns the open tabs, in the order they opened. */ tabs(): readonly BrowserTab[]; /** * Runs a trigger and waits for the tab it opens, then resolves with that * tab once it is the active tab. The wait takes the first tab the app * opens after it starts, which can be one an earlier action opened whose * page loaded only now. Rejects with `ACTION_FAILED` when no tab opens * within the timeout, naming the page when a tab was still loading it. */ waitForPopup(trigger: () => Promise, options?: { timeout?: number }): Promise; /** Opens a blank tab in the same browser context, sharing its cookies and storage, and makes it the active tab. */ newTab(): Promise; /** Runs a trigger and waits for its download. */ waitForDownload( trigger: () => Promise, options?: { timeout?: number }, ): Promise<{ path: string; absolutePath: string; suggestedFilename: string }>; /** Runs one trigger and waits for the requested number of completed downloads. */ waitForDownloads( trigger: () => Promise, options: { count: number; timeout?: number }, ): Promise; /** Viewport-level keyboard, for whatever has focus. */ readonly keyboard: { /** Sends one key. */ press(key: string): Promise; /** Holds one key until up; repeated down calls send a repeat event. */ down(key: string): Promise; /** Releases a held key. */ up(key: string): Promise; /** Types plain text. */ type(text: string): Promise; }; /** * Direct pointer input from test code, independent of agent observations. * After CDP recovery, test code can read current geometry with `evaluate` * before starting a pointer sequence. */ readonly mouse: { /** Moves the pointer. */ move(x: number, y: number): Promise; /** Scrolls the pointer wheel. */ wheel(deltaX: number, deltaY: number): Promise; /** Presses the primary pointer button. */ down(): Promise; /** Releases the primary pointer button. */ up(): Promise; }; /** The tools the active tab's page registers through WebMCP. See [WebMCP](#webmcp). */ readonly webmcp: { /** Returns the tools the page has registered now. */ tools(): Promise; /** Calls one tool and resolves with what its `execute` resolved to. */ callTool(name: string, input?: { readonly [key: string]: JsonValue } | null): Promise; }; /** Controls time in the attempt's pages. See [clock](#clock). */ readonly clock: BrowserClock; } ``` ### JsonValue ```ts /** A JSON scalar. */ export type JsonPrimitive = string | number | boolean | null; /** Data that survives JSON serialization. */ export type JsonValue = | JsonPrimitive | { readonly [key: string]: JsonValue } | readonly JsonValue[]; ``` ## Related The [browser guide](/browser) shows these members in recipes and covers [hosted browsers](/browser#hosted-browsers). The portable operations live on the [`app`](/reference/app) fixture.