Files
e2e/docs/reference/web.mdx
Krzysztof MochandOskar Kwaśniewski 847a09e6db feat(test)!: set fixtures up on demand, once per worker, and in beforeAll (#1891)
* feat(test): set fixtures up once per worker and pass them to beforeAll

test.extend() takes [fn, { scope: 'worker' }]: one instance per worker and
target, torn down when the worker ends. Suite hooks receive worker fixtures.
Engines can declare isolation: 'worker'; @e2e-dev/mobile does, so its device,
app, and screen reach beforeAll, afterAll, and worker fixtures.

Refs ENG-1297

* feat(e2e)!: set up fixtures on demand

A test now sets up only the test.extend() fixtures its body and its
beforeEach and afterEach hooks name in their first parameter, the fixtures
those name, and the auto ones. A suite hook sets up the worker fixtures it
names and the auto worker fixtures. Names are read from the function's
source, as Playwright and Vitest read them.

- [fn, { auto: true }] and [fn, { scope: 'worker', auto: true }] run a
  fixture nothing names.
- A fixture can name the fixtures declared beside it in the same extend()
  call. Fixtures run in declaration order, each after the ones it names.
- The attempt is resolved as one unit before the session launches: a
  fixture only an afterEach names is set up before the first beforeEach.
  An afterEach that names a fixture whose setup failed is skipped.
- Fixture rules fail as COLLECTION_ERROR with the file and line of the
  code: a parameter that is not destructured or takes a rest property, and
  a cycle, when the file is collected; a name the target lacks, a test
  fixture named by a suite hook or a worker fixture, and a fixture named
  like an engine's, at selection, for the pairs that run on that target.
- On an engine with isolation: 'worker', a suite hook or a worker fixture
  teardown that names no engine-backed fixture opens no engine attempt.

BREAKING CHANGE: a fixture nothing names no longer runs unless it is
declared with auto: true, and a test body, hook, or fixture function that
takes the whole fixture object (async (fixtures) => {}) no longer loads.

Refs ENG-1297

* refactor(core): declare core fixtures in one table

The five core fixtures (agent, app, screen, platform, session) are one
table in @e2e-dev/core: name, scope, and factory. createFixtures builds
the built-ins object through one loop over that table and the engine's
factories, every fixture a lazy accessor behind the same gate as before.

The runner's fixture pool, test.extend() validation, and launch read the
names and scopes from the table, so the name lists and the per-name scope
checks are gone. A launch session exposes the core fixtures that do not
belong to a test: app, screen, platform.

No behaviour change. app and screen were built with the attempt and are
now built on first read, like agent and the engine's fixtures.

Refs ENG-1297

* feat(e2e): extend a built-in fixture through test.extend

A test.extend() fixture named like one the test already has extends it,
by Playwright's rule: inside its function its own name is the fixture it
extends (the built-in, or an earlier fixture of that name), and tests,
hooks, and other fixtures that name it receive what it hands to use().

  base.extend({ device: async ({ device }, use) => {
    await device.setPermission('camera', 'deny');
    await use(device);
  } })

- A plain function takes the scope the extended fixture has on the
  target: device is a worker fixture on mobile, so its override runs once
  per worker and reaches beforeAll; app is a test fixture on web and a
  worker fixture on mobile. A declared scope that differs is a
  COLLECTION_ERROR naming both.
- A worker-scoped override receives what a worker fixture receives for
  that built-in, the forwarder to the attempt that is running.
- On a target without the built-in nothing fails until code that runs
  there names it; then the target has no such fixture.
- Only user code sees the override: the attempt's own built-ins, which the
  runner and the worker fixtures' forwarders read, are untouched.
- Types: the override keeps the extended fixture's type and scope, through
  an extend() overload that takes overrides without type arguments.

A fixture named like a core fixture, an engine's, or an earlier one of the
chain was refused before.

Refs ENG-1297

* docs(fixtures): name built-in fixtures and give their scope per engine

The docs now use one term, built-in fixtures, for agent, app, screen,
platform, session, and the ones an engine contributes (browser, device),
where pages said core fixtures, contributed fixtures, or engine fixtures.

The test reference gets one table with each built-in fixture's scope on
web and on mobile, and says what the scope decides: a test fixture reaches
test bodies, beforeEach, and afterEach; a worker fixture also reaches
beforeAll, afterAll, and worker fixtures. The hooks, worker fixtures, and
override sections link to it, as do the fixtures guide and the engine
pages. The Japanese and Chinese pages carry the table and the same terms.

Refs ENG-1297

* docs(ja): translate the fixture scope and on-demand changes

* docs(zh): translate the fixture scope and on-demand changes

* fix(e2e): let a worker fixture name an extended app or screen

A fixture that extends `app` or `screen` was taken for a test fixture when
its test.extend() call was checked, before any target is known. A worker
fixture declared after it that names `app` then failed at import on every
target, though the same fixture is accepted without the override and the
plan resolves both to worker scope on an engine whose state outlives a
test.

The scope of a plain function is now unresolved until a target is known,
whatever it extends, as it already was for an engine's own fixtures.

Refs ENG-1297

* fix(e2e): fail a suite hook that left an engine step running

On an engine whose state outlives a test, a beforeAll or afterAll hook, or
a worker fixture's teardown, can start a device step and not await it. The
hook's attempt then closed under the step, and its failure arrived later
as a stray rejection charged to whichever test ran then.

The suite attempt now does what a test attempt does once its body settled:
the step is failed at its call and cancelled, its outcome is awaited within
the cleanup budget, and the hook fails with STEP_NOT_AWAITED (HOOK_FAILED
for a suite hook).

The suite attempt keeps no step records, and StepRecorder dropped the
record of the step it had just opened before marking it running, so there
was nothing to abandon: a step now counts as running before the retained
window is trimmed.

Refs ENG-1297

* refactor(e2e): keep the fixtures a function names beside it

Registration parsed each test body, hook, and fixture function for the
fixtures it names, dropped the result, and left it in a WeakMap that the
planner and the pool read back with placeholder subjects. A cache miss
there would have named the wrong code and no line.

The parse result is now data: `names` on the registered test, the hook,
and the fixture definition. The planner and the pool read it, the WeakMap
and the per-function wrappers are gone, and one describeUser() gives an
error its subject. The explore test, registered by hand, parses its body
where it builds the record.

Unit tests state the names instead of generating source text for them.

Refs ENG-1297

* refactor(core): resolve built-in fixtures in one place

The core table declared the core fixtures, but what a target's built-in
fixtures are was still assembled around it: core names plus engine names in
three files, the 'engine' scope resolved in e2e through a cast into the
table, `platform` hard-coded as the one fixture that needs no attempt, and
two structural copies of the target.

core now exports builtInFixtures(target): names, scope(name),
needsAttempt(name), attemptless(name), and the unknown-fixture message,
over one BuiltInTarget. `platform` declares in the table that the target
alone decides it. launch, the planner, and the pool read from it.

DECLARED_BUILT_INS is the same view before a target is known: a scope the
engine decides is 'unresolved'. The planner takes either one, so its
no-target mode and the `target === undefined` branches through scopeOf and
read are gone. The scope of a fixture that extends `app` before a target
is known is 'unresolved' by construction.

Refs ENG-1297

* refactor(e2e): hand each function the fixtures it names

Every test body, hook, and fixture function must destructure its first
parameter, so what it reads is known before it runs. bindFixtures still
built a Proxy-gated bag for arbitrary property reads: one value in three
stores, the gate run twice (once over a faked plan), a third derivation of
scope, and an own-name shadow that re-derived what the planner had resolved.
No test code could reach the gate's throwing branches; only unit tests did,
by reading the bag directly.

The plan now records, per function, what each name it reads resolved to: a
chain fixture or a built-in. The pool hands each function a plain object
with exactly those names, the value a chain fixture handed over, or a
built-in read off the attempt when the function destructures it, so
built-ins stay lazy. An override that names itself receives the fixture it
extends because that is what its own name resolved to.

- bound.call(user) replaces user.fn(bound.fixtures); ready(user) asks
  whether every chain fixture it names was provided.
- attemptlessBuiltIns is a function from a name to a value that throws the
  reason for a built-in that needs an attempt.
- The planner runs once: it records what each fixture names, and the order
  is one declaration-order walk over that record. A second validating pass
  only reordered.

Behaviour: a bound or native function, whose parameters cannot be read, is
a COLLECTION_ERROR; it used to parse as naming nothing and still got lazy
built-ins. The docs no longer promise hooks and the body one shared object.

Refs ENG-1297

* refactor(e2e): move the suite attempt out of TargetExecutor

dispose, openSuiteHooks, and openSuiteAttempt were 177 lines of a second
attempt lifecycle inside TargetExecutor, written as closures in one method.

run/suite-attempt.ts now owns it: a SuiteAttempt class with open, acquire,
within, and close, over a SuiteAttemptHost interface the executor satisfies
(the way serial.ts borrows it through SerialHost), plus the worker
fixtures' teardown pass. It is the realm's SuiteHookSession itself, so the
executor keeps a context object and two call sites.

The three branches that built an attemptless reader with a "not available
to the <label>" error are one NoAttempt value ('isolated', 'unnamed',
'interrupted', or the launch failure) and one mapper to the message.

execute.ts: 1244 lines to 1052.

Refs ENG-1297

* refactor(e2e): share the attempt's fixture sequence

A run's attempt and an `e2e mcp` session's test each planned the test's
fixtures, bound them, entered the worker pool, set them up, ran the
beforeEach hooks and the body, filtered the afterEach hooks that can still
run, and labelled the teardowns. This PR widened that copy, and
standalone-test.ts asked the realm for the same hooks four times.

planAttemptFixtures(target, test, hooks) plans before any session exists
and returns open(), which binds the plan to the attempt: enter(), run()
for setup, hooks, and body, and cleanup() for the labelled afterEach hooks
and teardowns. Both call sites keep their own phases, budgets, and error
handling around it.

execute.ts: 1052 lines to 1031, its size on main.

Refs ENG-1297

* refactor(e2e): open the suite-hook pass without a lazy thunk

withSuiteHooks handed its work a thunk that opened the pass on first use.
Opening one does no I/O: the suite attempt launches nothing until a hook
that names an engine fixture runs. The pass is now opened up front and
closed in finally, and the `opened` slot and the `hooks()` call form go.

Refs ENG-1297

* refactor(e2e): ask the registry which hooks apply to a test

The selection-time fixture check rebuilt the scope chain of a test and
filtered the file's hooks by it, which the realm already did its own way.
registry.ts now exports scopeChain(test) and hooksFor(registration, test),
and both use them.

Refs ENG-1297

* refactor(core): move the fixture types into types/fixtures.ts

types.ts grew from 1679 to 1798 lines in this PR. The fixture scope, the
worker fixtures, and what test.extend() takes (definitions and overrides)
are one coherent group that nothing else in the file defines against, so
they move to types/fixtures.ts and types.ts re-exports them. The public
surface is the same.

types.ts: 1798 lines to 1715.

Refs ENG-1297

* refactor(core): drop the redundant override branch in FixtureDefinitions

A fixture that extends one the base already has was typed three ways: a
conditional branch inside the `Extra` map of FixtureDefinitions, the
`& FixtureOverrides` intersection, and the extend(overrides) overload.

Compiling the type tests without each in turn: the intersection types an
override written beside new fixtures with type arguments, and the overload
types an override-only call without them; both fail the tests when
removed. The conditional branch does not: with it gone the tests pass, and
a base name in `Extra` is `never` again, as it was before overrides. It is
removed, and the reference's copy of the declaration follows.

Refs ENG-1297

* refactor(e2e): split fixture errors from the parser, share hookLog

fixture-names.ts parses a parameter list, and also held FixtureUseError and
declarationSite, which format an error. They move to fixture-errors.ts.
Its identifier pattern held two raw zero-width characters; they are
written as escapes now.

hookLog and LOG_MODULE were pasted into three integration tests; they are
one helper in tests/helpers/hook-log.ts.

Refs ENG-1297

* docs(e2e): name the scope rule in the selection check's summary

The summary of assertFixtureUse still listed a chain fixture named like an
engine's as an error. Such a fixture extends the built-in now; the rule
left is a declared scope that differs from the extended fixture's.

Refs ENG-1297

* refactor(e2e): take execute.ts under 1000 lines

Two more pieces that are not the attempt's own sequence leave the file.

- Holding steps for `e2e run --step`: reading the screen a hold starts on
  and wiring AttemptHolds to the runner's hook move to step-hold.ts, beside
  the holds they configure (holdAttemptSteps, readHeldScreen).
- The result of a finished test or setup unit is a pure function of the
  pair, the verdict, the attempts, and a beforeAll failure: unitResult in
  units.ts, beside pairResult.

execute.ts: 1031 lines to 956. It was 1031 on main and 1226 at the review.

Refs ENG-1297

* test(e2e): match the not-awaited message without a step label

Main's #1880 names an unlabeled step by its api alone ("gadget.hang
finished"), where the message used to quote an empty label. The suite-hook
test's pattern required a label between the two, so it failed on the merge
with main.

* feat(e2e): an override inherits auto from the fixture it extends

A fixture that extends another and does not state `auto` now has the
extended fixture's, the way it has its scope: an override of an auto
fixture is set up for every test, and one of a built-in fixture on demand.
An `auto` that differs from the extended fixture's is a COLLECTION_ERROR
naming both, worded like the scope mismatch. This matches Playwright.

It also fixes which fixtures the plan starts from. An auto fixture was a
root by its own flag, so with an auto base and its override in one chain
the base was set up and the override skipped, while the name resolved to
the override; an override that replaced the base without naming it still
left the base running. An auto fixture is now a root only where its name
stands for it: the base runs once through the override's own name, or not
at all when the override replaces it.

Refs ENG-1297

* fix(core): name the hook or fixture that left a step running

STEP_NOT_AWAITED said "the test body returned before ..." for a step a
beforeAll, afterAll or beforeEach hook, a fixture's setup or a worker
fixture's teardown left running. The recorder now keeps the owner each
step was started under, and the runner says which code runs: the pool
for fixtures, hooks and the body, the suite attempt for suite hooks, and
a hosted session for itself.

---------

Co-authored-by: Oskar Kwaśniewski <oskar@okwasniewski.com>
2026-11-18 13:09:51 +00:00

1382 lines
53 KiB
Plaintext

---
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'` |
| [`viewport`](#viewport) | `ViewportSize \| null` | 1280 by 720 |
| [`screencast`](#screencast) | `WebScreencastOptions` | the viewport's size |
| [`connect`](#connect) | `WebConnectOptions` | launches locally |
| [`headers`](#headers) | `Record<string, string>` | - |
| [`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[]` | - |
- 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; see
[`permissions`](/reference/config#permissions).
- A target with `app.url` is a `browser` target, so `requires: ['browser']`
selects web targets.
- 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`), else every key. |
| `INVALID_CONFIG` | `headers`, `basicAuth`, `userAgent`, `locale`, or `timezoneId` 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`. |
#### `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.
#### `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<string | CdpTarget>;
reconnectEndpoint?(signal: AbortSignal): string | CdpTarget | Promise<string | CdpTarget>;
}
```
| Throws | When |
| --- | --- |
| `INVALID_CONFIG` | A `connect` without `cdpEndpoint`, or with one given as a string, at config load. Also `connect` beside a `browser` provider. |
<a id="recovering-a-cdp-transport" />
##### 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. |
| `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` (else `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.
<Note>
A persistent context does not support `headers`, `basicAuth`, `userAgent`,
`locale`, `timezoneId` (see [Options](#options)), `app.clearState`, or
session state capture and restore. `app.clearState` fails with
`UNSUPPORTED_CAPABILITY`. `app.restart` remains available.
</Note>
#### `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). |
<Note>
`headers` enables request routing, which disables the browser's HTTP cache and
blocks service workers.
</Note>
#### `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. |
<Note>
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.
</Note>
<Warning>
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)).
</Warning>
#### `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`, `waitForResponse`, `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`, and
`addInitScript`.
- `setViewport` sizes the active tab and every tab opened after it.
- [`emulateMedia`](#media-emulation) changes media on all open and future 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 until
`waitForPopup` or `activate` makes another one active. See [Tabs](#tabs).
- Every `browser` call is a recorded `browser.<method>` 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 `requires: ['browser']` in a suite that also runs on other
platforms.
- `expect(browser)` returns the `BrowserExpectation` the engine attaches:
`toHaveURL`, `toHaveTitle`, and `toHaveClass`. See
[browser matchers](/reference/expect#browser-matchers).
| Member | Returns |
| --- | --- |
| [`goto`](#goto) | `Promise<void>` |
| [`reload`](#reload-back-forward) | `Promise<void>` |
| [`back`](#reload-back-forward) | `Promise<void>` |
| [`forward`](#reload-back-forward) | `Promise<void>` |
| [`url`](#url-title) | `Promise<string>` |
| [`title`](#url-title) | `Promise<string>` |
| [`waitForURL`](#waitforurl) | `Promise<void>` |
| [`locator`](#locator) | `Locator` |
| [`frameLocator`](#framelocator) | `FrameScreen` |
| [`evaluate`](#evaluate) | `Promise<T>` |
| [`addInitScript`](#init-scripts) | `Promise<void>` |
| [`route`](#route) | `Promise<void>` |
| [`unroute`](#unroute) | `Promise<void>` |
| [`unrouteAll`](#unrouteall) | `Promise<void>` |
| [`waitForResponse`](#waitforresponse) | `Promise<WebResponse>` |
| [`cookies`](#cookies) | `Promise<Cookie[]>` |
| [`setCookies`](#setcookies) | `Promise<void>` |
| [`clearCookies`](#clearcookies) | `Promise<void>` |
| [`setViewport`](#setviewport) | `Promise<void>` |
| [`emulateMedia`](#media-emulation) | `Promise<void>` |
| [`onDialog`](#ondialog) | `Promise<() => Promise<void>>` |
| [`tabs`](#tabs) | `readonly BrowserTab[]` |
| [`waitForPopup`](#tabs) | `Promise<BrowserTab>` |
| [`newTab`](#tabs) | `Promise<BrowserTab>` |
| [`waitForDownload`](#waitfordownload) | `Promise<{ path, absolutePath, … }>` |
| [`waitForDownloads`](#waitfordownloads) | `Promise<{ path, absolutePath, … }[]>` |
| [`keyboard`](#keyboard) | `{ press, down, up, type }` |
| [`mouse`](#mouse) | `{ move, wheel, down, up }` |
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).
`locator` and `frameLocator` touch no page and take none.
A `{ timeout }` option overrides the budget on `goto`, `reload`, `back`,
`forward`, `waitForResponse`, `waitForPopup`, `waitForDownload`, and `waitForDownloads`, capped
by the test deadline (`cleanupTimeout` in `afterEach`); `0` waits until it. `url`, `title`, `evaluate`, `addInitScript`, `route`,
`unroute`, `unrouteAll`, `cookies`, `setCookies`, `clearCookies`, `setViewport`,
`emulateMedia`, `onDialog`, `newTab`, the `BrowserTab` methods, `keyboard.*`, and `mouse.*` take no override.
#### `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. |
| `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(/\/orders\/\d+$/, { timeout: 15_000 });
```
- A relative string resolves against the base URL and matches exactly after
normalization.
- A `RegExp` tests the full URL.
| Throws | When |
| --- | --- |
| `INVALID_ARGUMENT` | A pattern that is not a string or `RegExp` (a predicate function, say), or an option other than `timeout`, such as Playwright's `waitUntil`. |
| `ASSERTION_FAILED` | The URL did not match before the timeout. |
#### `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`). |
<Note>
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.
</Note>
#### `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<string>('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`. Else 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. |
#### `route`
Adds an attempt-scoped network route.
```ts
await browser.route('**/api/quote', async (route) => {
await route.fulfill({ json: { cents: 4200 } });
});
```
`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`, both tested against the full URL. In
a string, `*` matches within a path segment, `**` across `/`, `?` any one
character, and `\` escapes the next. `unroute` and `waitForResponse` take
the same patterns.
- 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 predicate function as the pattern. Also an option a decision does not take (Playwright's `abort(errorCode)`, a misspelled key): the request is aborted and the next step fails. |
| `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<string, string>;
/** 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<string, string | undefined>;
/** Request body. */
postData?: string;
}
export interface WebRoute {
/** The intercepted request. */
readonly request: {
readonly url: string;
readonly method: string;
readonly headers: Readonly<Record<string, string>>;
readonly postData?: string;
};
/** Reads upstream without deciding the route or following redirects. */
fetch(): Promise<WebResponse>;
/** Fulfills the intercepted request once. */
fulfill(response: RouteFulfillResponse): Promise<void>;
/** Sends the intercepted request to the network once, skipping every other route. */
continue(overrides?: RouteContinueOverrides): Promise<void>;
/** Hands the intercepted request to the route registered before this one, or the network when none matches. */
fallback(): Promise<void>;
/** Aborts the intercepted request once. */
abort(): Promise<void>;
}
```
#### `unroute`
Removes the attempt-scoped routes that match a pattern, in the
[`route`](#route) pattern syntax.
```ts
await browser.unroute('**/api/quote');
```
| Throws | When |
| --- | --- |
| `INVALID_ARGUMENT` | A predicate function as the pattern. |
#### `unrouteAll`
Removes every route registered by the browser fixture, preserving configured
headers.
```ts
await browser.unrouteAll();
```
#### `waitForResponse`
Waits for a response that matches a pattern, in the [`route`](#route) pattern
syntax.
```ts
const response = await browser.waitForResponse('**/api/orders');
expect(response.status).toBe(201);
```
- The deadline bounds the match: the response resolves as soon as its headers
arrive.
- `body()`, `text()`, and `json()` wait for the body on a budget of their own,
`config.actionTimeout` capped by the test deadline.
- `url`, `status`, and `headers` are always readable.
- A genuinely empty body reads as an empty `Buffer` from `body()` and `''`
from `text()`; `json()` rejects it.
| Throws | When |
| --- | --- |
| `INVALID_ARGUMENT` | A predicate function as the pattern. |
| `ACTION_FAILED` | Nothing matches inside the deadline. From `body()`, `text()`, and `json()`: a body still streaming when their budget runs out, or a body the browser could not read (a connection reset short of the declared `Content-Length`, a request the page aborted, or a redirect, whose body the browser never keeps), instead of an empty string. |
```ts
export interface WebResponse {
/** Response URL. */
readonly url: string;
/** HTTP status. */
readonly status: number;
/** Response headers, lower-cased names; `route.fetch()` joins several `set-cookie` values with `\n`, `waitForResponse` leaves cookie headers out. */
readonly headers: Readonly<Record<string, string>>;
/** Waits for the body and returns its bytes. */
body(): Promise<Buffer>;
/** Waits for the body and parses it as JSON. */
json<T = unknown>(): Promise<T>;
/** Waits for the body and reads it as text. */
text(): Promise<string>;
}
```
#### `cookies`
Returns the cookies visible to the current context.
```ts
const cookies = await browser.cookies();
```
#### `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 |
| --- | --- |
| `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()`.
#### `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<void>;
/** Dismisses the dialog once. */
dismiss(): Promise<void>;
}
export type DialogHandler = 'accept' | 'dismiss' | ((dialog: Dialog) => void | Promise<void>);
```
#### 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<string>;
title(): Promise<string>;
/** Whether this is the active tab. */
isActive(): boolean;
isClosed(): boolean;
/** Makes this the active tab. */
activate(): Promise<void>;
/** Closes the tab; the tab that opened it becomes active when it was. */
close(): Promise<void>;
}
```
| Throws | When |
| --- | --- |
| `ACTION_FAILED` | `waitForPopup`: no tab opened in time. A trigger that resolved in time fails with `no tab opened within <n>ms; the trigger resolved after <m>ms`, or with `the tab the app opened did not load <url> within <n>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 <n>ms; the trigger resolved after <m>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.
## 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:
<CodeGroup>
```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
```
</CodeGroup>
- 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.
- 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. |
## Types
The package exports these types for typing config helpers and fixtures:
`WebOptions`, `WebMedia`, `WebScreencastOptions`, `WebConnectOptions`,
`WebBasicAuth`, `WebInitScript`, `BrowserName`, `BrowserProvider`,
`BrowserProviderScope`, `BrowserRequest`, `BrowserLease`,
`BrowserReleaseContext`, `BrowserProviderDownloads`,
`BrowserDownloadContext`, `PlaywrightLiveSurface`, `Browser`, `FrameScreen`,
`BrowserExpectation`, `WebRoute`, `RouteFulfillResponse`,
`RouteContinueOverrides`, `WebResponse`, `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;
/**
* 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;
/**
* 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<Record<string, string>>;
/**
* 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[];
}
```
### `Browser` interface
```ts
/**
* The browser the attempt drives, showing one active tab. Navigation, reads,
* `locator`, `frameLocator`, `evaluate`, `waitForResponse`, `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<BrowserExpectation> {
/** Navigates to an allowed URL. */
goto(
url: string,
options?: {
waitUntil?: 'load' | 'domcontentloaded' | 'networkidle';
timeout?: number;
},
): Promise<void>;
/** Reloads the current document. */
reload(options?: ActionOptions): Promise<void>;
/** Navigates browser history back once. */
back(options?: ActionOptions): Promise<void>;
/** Navigates browser history forward once. */
forward(options?: ActionOptions): Promise<void>;
/** Returns the current URL. */
url(): Promise<string>;
/** Returns the current title. */
title(): Promise<string>;
/** Waits for the current URL to match. */
waitForURL(url: string | RegExp, options?: { timeout?: number }): Promise<void>;
/** 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<T extends JsonValue>(fn: string | (() => T | Promise<T>)): Promise<T>;
/** Evaluates trusted test code with one required JSON-safe argument. */
evaluate<T extends JsonValue, Arg extends JsonValue>(
fn: string | ((arg: Arg) => T | Promise<T>),
arg: Arg,
): Promise<T>;
/** Adds a script every document runs before the page's own, from the next navigation on. */
addInitScript(script: string | { path: string } | (() => unknown)): Promise<void>;
/** Adds an init script function called with one JSON argument. */
addInitScript<Arg extends JsonValue>(script: (arg: Arg) => unknown, arg: Arg): Promise<void>;
/** Adds an attempt-scoped network route. */
route(
pattern: string | RegExp,
handler: (route: WebRoute) => void | Promise<void>,
): Promise<void>;
/** Removes matching attempt-scoped routes. */
unroute(pattern: string | RegExp): Promise<void>;
/** Removes all routes registered by this browser fixture, preserving the configured headers. */
unrouteAll(): Promise<void>;
/** Waits for a matching response. */
waitForResponse(
pattern: string | RegExp,
options?: { timeout?: number },
): Promise<WebResponse>;
/** Returns cookies visible to the current context. */
cookies(): Promise<Cookie[]>;
/** Sets cookies after URL validation. */
setCookies(cookies: readonly Cookie[]): Promise<void>;
/** Removes matching cookies only; without filters removes every cookie, preserving other storage. */
clearCookies(options?: CookieFilter): Promise<void>;
/** Sets the viewport size. */
setViewport(size: { width: number; height: number }): Promise<void>;
/** Emulates CSS media features on every open tab and every tab opened after them. */
emulateMedia(media: WebMedia): Promise<void>;
/** Registers an attempt-scoped dialog handler and returns an unsubscribe function. */
onDialog(handler: DialogHandler): Promise<() => Promise<void>>;
/** 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<void>, options?: { timeout?: number }): Promise<BrowserTab>;
/** Opens a blank tab in the same browser context, sharing its cookies and storage, and makes it the active tab. */
newTab(): Promise<BrowserTab>;
/** Runs a trigger and waits for its download. */
waitForDownload(
trigger: () => Promise<void>,
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<void>,
options: { count: number; timeout?: number },
): Promise<readonly { path: string; absolutePath: string; suggestedFilename: string }[]>;
/** Viewport-level keyboard, for whatever has focus. */
readonly keyboard: {
/** Sends one key. */
press(key: string): Promise<void>;
/** Holds one key until up; repeated down calls send a repeat event. */
down(key: string): Promise<void>;
/** Releases a held key. */
up(key: string): Promise<void>;
/** Types plain text. */
type(text: string): Promise<void>;
};
/**
* 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<void>;
/** Scrolls the pointer wheel. */
wheel(deltaX: number, deltaY: number): Promise<void>;
/** Presses the primary pointer button. */
down(): Promise<void>;
/** Releases the primary pointer button. */
up(): Promise<void>;
};
}
```
### 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.