> ## Documentation Index
> Fetch the complete documentation index at: https://e2e.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Browser

> API reference for @e2e-dev/web: web() options, the browser fixture for routes, dialogs, downloads, iframes, and cookies, hosted browser providers, and installs.

`@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"

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"

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](https://e2e.com/docs/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<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[]` | - |
| [`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`](https://e2e.com/docs/reference/config#permissions).
- The full declaration 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](https://e2e.com/docs/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](https://e2e.com/docs/integrations/lightpanda) or [Moli](https://e2e.com/docs/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](#hosted-browsers) has the `BrowserProvider`
  contract and an example provider.
- Two browsers on one app are two targets, as in
  [One size per target](https://e2e.com/docs/web#one-size-per-target). In CI, install each extra
  browser by name with the [install command](#installing-browsers).

```ts title="Target fragment"
{ name: 'webkit', engine: web({ browser: 'webkit' }), app },
```

| 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](https://e2e.com/docs/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. [Viewports](https://e2e.com/docs/web#viewports) shows a suite at several sizes.

| 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()`](https://e2e.com/docs/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`](https://e2e.com/docs/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. It defaults to the
  viewport's size, or the window's under `viewport: null`. A smaller size
  makes a smaller file.
- `quality` is the JPEG quality of each frame, an integer from 0 through
  100. Unset, it is Playwright's default.
- A provider that [records](#recording-on-the-provider) records in the
  screencast's place and ignores these options.
- Which attempts record is the config's [`video`](https://e2e.com/docs/reference/config#video)
  mode.

```ts
export interface WebScreencastOptions {
  readonly size?: ViewportSize;
  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 Chromium over CDP instead of launching one locally, or
to another browser that speaks CDP, such as a running
[Lightpanda](https://e2e.com/docs/integrations/lightpanda) or [Moli](https://e2e.com/docs/integrations/moli).

```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, or beside `browser: 'firefox'` or `'webkit'`. |

<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.
- A missing active tab or a different context fails the attempt. A matching
  URL does not select a replacement tab. Another tab of the attempt that is
  gone is dropped.

| 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.
- `browser.mouse` and `browser.keyboard` stay available without an agent
  observation. Read current geometry and focus with `browser.evaluate`
  before acting.
- Code that uses [`surfaceOf(engine)`](#surfaceof) must read its accessors
  again after recovery.

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.

To reuse one sign-in across files, keep isolated contexts (no
`reconnectEndpoint`, no provider `scope: 'attempt'`) and
[sign in once in a setup test](https://e2e.com/docs/authentication#reuse-authenticated-sessions).

<Note>
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.
</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.
- Names are case-insensitive. A configured header replaces a request's own
  header of the same name.
- `headers` and `basicAuth` are how a test reaches a
  [protected preview](https://e2e.com/docs/web#protected-previews).
- See [request credentials](https://e2e.com/docs/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` 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

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
export interface WebBasicAuth {
  readonly username: string;
  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](https://e2e.com/docs/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: `prefers-color-scheme` and `prefers-reduced-motion`. `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.
- `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
export interface WebMedia {
  readonly colorScheme?: 'light' | 'dark' | 'no-preference';
  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
web({ initScripts: [{ path: 'tests/init.js' }] }); // every test

await browser.addInitScript((value) => { Math.random = () => value; }, 0.5); // one test
await app.open('/raffle');
```

- A script is JavaScript source, `{ path }` to a file relative to the
  project root, or a function.
- 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
export type WebInitScript = string | { readonly path: string } | (() => unknown);
```

### The browser fixture

`browser` is the whole browser, showing one active tab. It holds the
browser-only work: routes, dialogs, downloads, cookies, and code that runs in
the page. For navigation, interactions, and checks, use `screen`, `app`, and
`expect`.

- What reads or acts on a page acts on the active tab: `goto`, `reload`,
  `back`, `forward`, `url`, `title`, `waitForURL`, `locator`, `frameLocator`,
  `evaluate`, `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 stays in the background until `waitForPopup` or
  `activate` makes it 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`.
- In a suite with device targets, add `{ platforms: ['web'] }` to a test
  that uses `browser`, so the runner skips it on devices.
- `expect(browser)` returns the `BrowserExpectation` the engine attaches:
  `toHaveURL`, `toHaveTitle`, and `toHaveClass`. See
  [browser matchers](https://e2e.com/docs/reference/expect#browser-matchers).

| Member | Returns |
| --- | --- |
| [`name`](#name-version) | `BrowserName` |
| [`version`](#name-version) | `string` |
| [`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<PageResponse>` |
| [`waitForRequest`](#waitforrequest) | `Promise<WebRequest>` |
| [`cookies`](#cookies) | `Promise<Cookie[]>` |
| [`setCookies`](#setcookies) | `Promise<void>` |
| [`clearCookies`](#clearcookies) | `Promise<void>` |
| [`setViewport`](#setviewport) | `Promise<void>` |
| [`emulateMedia`](#media-emulation) | `Promise<void>` |
| [`setNetwork`](#setnetwork) | `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 }` |
| [`webmcp`](#webmcp) | `{ tools, callTool }` |
| [`clock`](#clock) | `BrowserClock` |

The [config](https://e2e.com/docs/reference/config) sets each member's budget:

- `goto`, `reload`, `back`, and `forward`: [`timeout`](https://e2e.com/docs/reference/config#timeout),
  the same budget `app.open()` uses.
- `waitForURL`: [`assertionTimeout`](https://e2e.com/docs/reference/config#assertiontimeout).
- Every other member: [`actionTimeout`](https://e2e.com/docs/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`, `waitForURL`, `waitForResponse`, `waitForRequest`, `waitForPopup`, `waitForDownload`, and `waitForDownloads`, capped
by the test deadline (`cleanupTimeout` in `afterEach`); `0` waits until it.
No other member takes an 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'`: Chrome, Edge, and a CDP server that isn't Chromium,
  such as [Lightpanda](https://e2e.com/docs/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](https://e2e.com/docs/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.

```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. A glob matches
  a character the browser percent-encodes in a URL (non-ASCII text, a
  space, `"`, `<`, `>`) written as itself.
  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.
- Use `filter({ has })` for an element that contains another.
- Use a selector only when role, label, and test-id queries can't find the
  element. For a match made ambiguous by a hidden duplicate, try
  `{ visible: true }` first.
- `locator` stops at a closed shadow root, which `screen` queries reach into.
  See [Shadow DOM](#shadow-dom).

| Throws | When |
| --- | --- |
| `INVALID_LOCATOR` | An empty selector, or a `*` capture before the last part (`*css=article >> text=Hello`). |

#### `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. In a frame, `locator` takes a CSS or XPath selector, and
`frameLocator` enters a nested frame. Use the frame's `locator` only when the
control has no accessible name, label, placeholder, or test id.

```ts
const editor = browser.frameLocator('#result');
await editor.locator('#upload').setInputFiles('fixtures/photo.png');
await expect(editor.frameLocator('#preview').getByRole('heading', 'Uploaded')).toBeVisible();
```

A frame from another site, such as a hosted card field, needs `frameLocator`
for its steps:

- The agent's semantic tree shows that frame as an `iframe` element with none
  of its content ([site check](https://e2e.com/docs/reference/security#site-check)). The agent
  reaches the content only through screenshots.
- To judge its content with `agent.assert`, pass
  [`vision`](https://e2e.com/docs/reference/agent#vision).
- An `agent.act` whose only change is in that frame never records a
  [replay](https://e2e.com/docs/cache#when-a-recording-is-written).

```ts
export interface FrameScreen extends Screen {
  locator(selector: string): Locator;
  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, so it cannot 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.
- Use `evaluate` only for state that `screen` can't read.

| 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 } });
});

await app.open('/checkout');
await expect(screen.getByText('$42.00')).toBeVisible();

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.

- The pattern is a string or a `RegExp`, read as [`waitForURL`](#waitforurl)
  reads one, so a string with no wildcard is an exact URL.
- `{ method, url }` narrows the pattern to one HTTP method too. `method` is
  case-insensitive.
- `unroute`, `waitForResponse`, and `waitForRequest` take the same patterns.
- 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 answers requests made after it is registered, also on an open
  page. Register it before the page opens to answer a request the page
  makes as it loads.
- 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`.
- `fulfill` answers the request. `continue` sends it to the network and
  skips every other route. `fallback` hands it to the route registered
  before this one, or to the network when none matches. `abort` aborts it.
- A `continue` URL goes through the same rule as `goto` and must keep the
  request's scheme. `continue` headers replace every request header, with
  the configured `headers` added on top. A `continue` header set to
  `undefined` is dropped, also on redirects.
- A `fulfill` takes one of `json`, `body`, or `path`, or none for an empty
  body. A `body` is a string or bytes (`Buffer`, `Uint8Array`), sent as is.
  A `path` names a file relative to the project root, and its `Content-Type`
  follows its extension unless `contentType` or a `content-type` header sets
  one.
- 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
export type RouteFulfillResponse = {
  status?: number;
  headers?: Record<string, string>;
  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 }
);

export interface RouteContinueOverrides {
  url?: string;
  method?: string;
  headers?: Record<string, string | undefined>;
  postData?: string;
}

export interface RouteMatcher {
  readonly method: string;
  readonly url: string | RegExp;
}

export interface WebRequest {
  readonly url: string;
  readonly method: string;
  readonly headers: Readonly<Record<string, string>>;
  readonly postData?: string;
}

export interface WebRoute {
  readonly request: WebRequest;
  fetch(): Promise<WebResponse>;
  fulfill(response: RouteFulfillResponse): Promise<void>;
  continue(overrides?: RouteContinueOverrides): Promise<void>;
  fallback(): Promise<void>;
  abort(): Promise<void>;
}
```

| `WebRequest` field | Description |
| --- | --- |
| `method` | As the page sent it. |
| `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`. |
| `postData` | The body as text. Absent when the request has none. |

#### `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`.
- A predicate runs once per response with a `PageResponse`. Any truthy
  value matches. Async predicates can run at the same time on several
  responses, and the first to match wins.
- 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.
- On the returned `PageResponse`, `body()`, `text()`, and `json()` each use
  `config.actionTimeout`, capped by the test deadline.
- 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
export interface WebResponse {
  readonly url: string;
  readonly status: number;
  readonly headers: Readonly<Record<string, string>>;
  body(): Promise<Buffer>;
  json<T = unknown>(): Promise<T>;
  text(): Promise<string>;
}

export interface PageResponse extends WebResponse {
  readonly request: WebRequest;
}
```

| `WebResponse` field | Description |
| --- | --- |
| `headers` | Lower-cased names. `waitForResponse` leaves cookie headers out. |

#### `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`. 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.
- `expires` is a Unix timestamp in whole seconds.

| 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 {
  name: string;
  value: string;
  expires?: number;
  httpOnly?: boolean;
  secure?: boolean;
  sameSite?: 'Strict' | 'Lax' | 'None';
}

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, so the next `app.open` loads at
  that size.
- 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`](https://e2e.com/docs/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();
```

- An unhandled `alert`, `confirm`, or `prompt` fails the next step, so
  register the handler before the action that opens the dialog.
- The handler is `'accept'`, `'dismiss'`, or a function that receives the
  `Dialog`.
- A function handler must call `accept(text?)` 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
export interface Dialog {
  readonly type: 'alert' | 'confirm' | 'prompt' | 'beforeunload';
  readonly message: string;
  accept(text?: string): Promise<void>;
  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. 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. A provider's own recording covers
  every tab.

```ts
export interface BrowserTab {
  url(): Promise<string>;
  title(): Promise<string>;
  isActive(): boolean;
  isClosed(): boolean;
  activate(): Promise<void>;
  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(),
);
const csv = await readFile(file.absolutePath, 'utf8');
expect(csv).toContain('Invoice');
```

- 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. `path` is relative to the attempt's artifact directory,
  not to the project.
- On a hosted browser the file comes back through the provider's
  [`downloads`](#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');
```

- `press(key)` sends one key. `down(key)` holds a key until `up(key)`
  releases it, and a repeated `down` sends a repeat event.
- `type(text)` types plain text only, never a `Secret`.
- Prefer `locator.press` and `locator.fill` when a target exists.

#### `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();
```

`move(x, y)` moves the pointer, `wheel(deltaX, deltaY)` scrolls, and `down`
and `up` press and release the primary button.

#### 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"

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. 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`.
  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
export interface WebMcpTool {
  readonly name: string;
  readonly description: string;
  readonly inputSchema?: JsonValue;
  readonly annotations?: {
    readonly readOnly?: boolean;
    readonly untrustedContent?: boolean;
    readonly consequential?: boolean;
  };
}
```

| Annotation | Description |
| --- | --- |
| `readOnly` | The tool changes no state. |
| `untrustedContent` | The tool's output may carry third-party content. |
| `consequential` | The tool takes a consequential action, such as placing an order. |

`inputSchema` is the JSON Schema of the tool's input.

| 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.
- After `app.clearState()` or a session restore, 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`.
- 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
export type ClockTime = number | string | Date;

export type ClockTicks = number | string;

export interface BrowserClock {
  install(options?: { time?: ClockTime }): Promise<void>;
  fastForward(ticks: ClockTicks): Promise<void>;
  runFor(ticks: ClockTicks): Promise<void>;
  pauseAt(time: ClockTime): Promise<void>;
  resume(): Promise<void>;
  setFixedTime(time: ClockTime): Promise<void>;
  setSystemTime(time: ClockTime): Promise<void>;
}
```

| 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. An app that depends
on Playwright itself keeps its own copy, and 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 the browsers for the engine's pinned Playwright as their own step,
in CI or a container image, run the package's command:

<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. When chromium or firefox is installed without them,
  [`e2e doctor`](https://e2e.com/docs/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.

## Hosted browsers

A browser provider leases a browser from a service and gives the engine its
CDP endpoint. Pass it as [`browser`](#browser). The runner releases each
lease when its scope ends, also after a failure or Ctrl-C. A worker that
crashes or is killed first leaves an orphan for the provider's
[`sweep`](#pick-a-lease-scope) or the service's own expiry.

| Service | Provider |
| --- | --- |
| [Kernel](https://e2e.com/docs/integrations/kernel) | `kernel()` from `@e2e-dev/kernel` |
| [Notte](https://e2e.com/docs/integrations/notte) | `notte()` from `@e2e-dev/notte` |
| [smol machines](https://e2e.com/docs/integrations/smol) microVMs on your own computer | `smol()` from `@e2e-dev/smol` |
| [Lightpanda](https://e2e.com/docs/integrations/lightpanda), the open-source headless browser, on your own machine | `lightpanda()` from `@e2e-dev/lightpanda` |
| [Moli](https://e2e.com/docs/integrations/moli), a local browser with on-demand layout and screenshots | `moli()` from `@e2e-dev/moli` |
| [TestMu AI](https://e2e.com/docs/integrations/testmu#run-web-targets-in-browsers) | `testmuBrowsers()` from `@e2e-dev/testmu/web` |
| [E2B](https://e2e.com/docs/integrations/e2b#run-web-targets-in-browsers) sandboxes | `e2bBrowsers()` from `@e2e-dev/e2b/web` |
| [Revyl](https://e2e.com/docs/integrations/revyl#run-web-targets-in-browsers) | `revylBrowsers()` from `@e2e-dev/revyl/web` |
| Any other service | Your own provider, a few dozen lines in your project |

When the service shows the window in a live view, add `viewport: null` so
the page [fills the window](https://e2e.com/docs/web#fill-the-window). A target with nothing to
run leases nothing.

### Write a provider

A provider implements this interface:

```ts
export interface BrowserProvider {
  readonly name: string;
  readonly scope?: 'worker' | 'attempt';
  acquire(request: BrowserRequest): Promise<BrowserLease>;
  release(lease: BrowserLease, context: BrowserReleaseContext): Promise<void>;
  cdpHeaders?(lease: BrowserLease, context: BrowserRequest): Readonly<Record<string, string>> | Promise<Readonly<Record<string, string>>>;
  record?(lease: BrowserLease, context: ProviderRecordContext): Promise<ProviderRecording>;
  readonly downloads?: BrowserProviderDownloads;
  sweep?(context: BrowserReleaseContext): Promise<readonly string[]>;
}

export interface BrowserProviderDownloads {
  readonly dir: string;
  read(lease: BrowserLease, file: string, context: BrowserDownloadContext): Promise<Uint8Array>;
}

export interface BrowserLease {
  readonly id: string;
  readonly cdpEndpoint: string;
  readonly reconnectEndpoint?: string;
}
```

| Field | Description |
| --- | --- |
| `BrowserProvider.name` | The label in progress lines and error messages. |
| `BrowserProvider.sweep` | Resolves to the ids of the leases it released. |
| `BrowserProviderDownloads.dir` | An absolute directory on the browser's machine. |
| `BrowserLease.cdpEndpoint` | A `ws://`, `wss://`, or `http://` DevTools endpoint. |
| `BrowserLease.reconnectEndpoint` | For `scope: 'attempt'` leases only. |

`acquire` gets the run id, the target, the worker slot and slot count, the
attempt id for a per-attempt lease, the run's environment, an abort signal,
and a `log` that reaches the reporter. Read tokens from `request.env`, not
`process.env`.

A lease is JSON data. `release` gets back the object `acquire` returned, so
a provider can keep its own fields on it. Only `id`, `cdpEndpoint`, and
`reconnectEndpoint` travel to the worker, so key anything a worker uses,
such as a recording, on `lease.id`.

For an authenticated CDP connection, implement `cdpHeaders(lease, request)`
and read credentials from `request.env` in the worker. Headers never travel
in lease JSON and do not become page request headers.

<Accordion title="Example provider and config">

```ts title="browser-provider.ts"

/**
 * Leases browsers from a service that starts a Chromium per session and
 * exposes its DevTools endpoint. Replace the three requests with your
 * service's API.
 */
export function hostedBrowsers(options: { serviceUrl: string; scope?: 'worker' | 'attempt' }): BrowserProvider {
  return {
    name: 'hosted-browsers',
    scope: options.scope ?? 'worker',
    async acquire(request) {
      const token = request.env['BROWSER_SERVICE_TOKEN'];
      if (token === undefined || token === '') throw new Error('BROWSER_SERVICE_TOKEN is not set');
      const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
      // 1. Ask for a browser; name the session after the run so it can be found later.
      const created = await fetch(`${options.serviceUrl}/sessions`, {
        method: 'POST',
        headers,
        body: JSON.stringify({
          name: `e2e ${request.runId} ${request.targetName} ${request.attemptId ?? `slot ${request.slot + 1} of ${request.slots}`}`,
        }),
        signal: request.signal,
      });
      if (!created.ok) throw new Error(`browser service: HTTP ${created.status}`);
      const { id } = (await created.json()) as { id: string };
      // 2. Wait until the session exposes its DevTools endpoint.
      for (;;) {
        const response = await fetch(`${options.serviceUrl}/sessions/${id}`, { headers, signal: request.signal });
        const session = (await response.json()) as { status: string; cdpUrl?: string; viewerUrl?: string };
        if (session.status === 'ready' && session.cdpUrl !== undefined) {
          if (session.viewerUrl !== undefined) request.log(`watch at ${session.viewerUrl}`);
          return { id, cdpEndpoint: session.cdpUrl };
        }
        if (session.status !== 'starting') throw new Error(`browser service: session ${id} is ${session.status}`);
        await new Promise((resolve) => setTimeout(resolve, 2_000));
      }
    },
    async release(lease, context) {
      // 3. Stop the session; the run waits for this within cleanupTimeout.
      const token = context.env['BROWSER_SERVICE_TOKEN'] ?? '';
      await fetch(`${options.serviceUrl}/sessions/${lease.id}/stop`, {
        method: 'POST',
        headers: { Authorization: `Bearer ${token}` },
        signal: context.signal,
      });
    },
  };
}
```

```ts title="e2e.config.ts"

export default {
  targets: [
    {
      name: 'hosted',
      engine: web({
        browser: hostedBrowsers({ serviceUrl: 'https://browsers.example.com' }),
      }),
      app: { url: 'https://staging.example.com' },
    },
  ],
  workers: 2,
} satisfies E2EConfig;
```

Two workers lease two sessions in parallel and keep them for the run.

</Accordion>

### Pick a lease scope

`scope: 'worker'`, the default, keeps one browser per worker slot for the
whole run. `scope: 'attempt'` gives each attempt, retries included, a fresh
browser that no earlier test touched, for the cost of a session start per
attempt.

A worker that crashes or gets killed can't release its leases. Implement
`sweep` to clean up any orphaned leases at the end of a run (once per
target, using provider tags or a local lease journal). A failed sweep logs a
line without failing the run. Without `sweep`, orphaned browsers stay open
until the service ends them.

<Accordion title="Worker scope: when leases start and end">
- All worker slots lease their browsers in parallel at startup; if any slot
  fails, the run aborts before tests begin and releases the rest.
- Leases are released after the last worker exits (within `cleanupTimeout`),
  even on failures or Ctrl-C.
- If a worker's browser drops mid-run, the worker leases a replacement on
  the next attempt and releases it on exit. Because `acquire` can run inside
  a worker process, don't rely on in-memory state from the main process.
</Accordion>

<Accordion title="Attempt scope: limits">
Attempt-scoped tests run in the browser's persistent default context on its
first tab, with the limits and the reconnect behavior under
[Recovering a CDP transport](#recovering-a-cdp-transport).
</Accordion>

### Downloads on the provider

Implement `downloads` so `browser.waitForDownload` works on remote browsers.
The browser saves files under `dir`, and each finished path goes to `read`
to fetch the bytes through the provider's API (see
[Kernel](https://e2e.com/docs/integrations/kernel#downloads) or
[Notte](https://e2e.com/docs/integrations/notte#downloads)). Without `downloads`, calling
`waitForDownload` on a remote browser fails. Local browser providers don't
need it.

### Recording on the provider

Implement `record` to use the service's own recording as the attempt's
video. When an attempt records [video](https://e2e.com/docs/reference/config#video), the worker
calls `record` instead of starting the engine's screencast, once the page
is open. The recording covers the whole browser window, tabs and address
bar included.

`record` returns a `ProviderRecording` from `e2e/engine`. When the attempt
collects its video, its `stop` does one of two things:

- Writes a file into the directory it gets and returns `{ file }`. e2e keeps
  it as `video/<file>` beside the attempt's other artifacts.
- Returns `{ url, mediaType }` for a recording the service keeps. The
  report links to it.

<Accordion title="Example record method">

```ts title="browser-provider.ts"

// In hostedBrowsers(), beside acquire and release.
async record(lease, context): Promise<ProviderRecording> {
  const headers = { Authorization: `Bearer ${context.env['BROWSER_SERVICE_TOKEN'] ?? ''}` };
  const startedAt = new Date().toISOString();
  const started = await fetch(`${options.serviceUrl}/sessions/${lease.id}/recordings`, {
    method: 'POST',
    headers,
    signal: context.signal,
  });
  if (!started.ok) throw new Error(`browser service: HTTP ${started.status}`);
  const { id } = (await started.json()) as { id: string };
  return {
    startedAt,
    async stop({ signal }) {
      const stopped = await fetch(`${options.serviceUrl}/recordings/${id}/stop`, { method: 'POST', headers, signal });
      if (!stopped.ok) throw new Error(`browser service: HTTP ${stopped.status}`);
      // The service keeps the recording; the report links to its player page.
      return { url: `${options.serviceUrl}/recordings/${id}`, mediaType: 'text/html' };
    },
  };
},
```

</Accordion>

A failed `record` fails the attempt's launch, naming the provider and the
lease. A failed `stop` runs one more time when the attempt ends, so no
recording keeps running on a shared browser. When the service can't record
a browser (a headless one, say), leave `record` out and the engine records
the screencast. [Kernel](https://e2e.com/docs/integrations/kernel#recordings) records this way.

## Shadow DOM

`screen` queries, scopes, and `has` filters reach into open and closed
shadow roots, and the agent sees their content. `first`, `last`, and `nth`
count the matches outside a closed root first, then each root's matches in
order.

```ts
// The input and the button live in a closed shadow root a widget attached.
await screen.getByPlaceholder('Access code').fill('SHADOW-42');
await screen.getByRole('button', 'Submit').tap();
await expect(screen.getByText('Access granted')).toBeVisible();
```

`browser.locator`, `frameLocator`, and `filter({ hasText })` stop at a
closed root. Query the text inside the root instead, or filter with `has`.
A closed root declared in HTML (`<template shadowrootmode="closed">`) is out
of reach.

## Inert content

The agent doesn't see inert content, so it never aims at a control that
takes no input:

- An element with the `inert` attribute, and everything under it.
- Everything outside a modal `<dialog>`, opened with `showModal()` or a
  `show-modal` command. With several open, only the one shown last stays.
  When e2e can't tell which one that is, it leaves out nothing.

Locators still find inert content, and `toBeVisible` still passes, as in
Playwright.

## Icon fonts and generated content

Text that a stylesheet adds with `::before` or `::after` is part of a
control's name, as screen readers read it: a button with
`.next::before { content: "→" }` is `button "→ Next"`. Label text, as
`getByLabel` reads it, never includes generated content.

Icon fonts are the exception. Font Awesome and similar fonts draw each icon
from a private-use character (`\f090`), and the engine drops those
characters from every name:

- `<button><i class="fa fa-sign-in"> Login</i></button>` is
  `button "Login"`, and `getByRole('button', 'Login')` finds it.
- A glyph between two words reads as a space.
- A control with only an icon reads as its `title`, when it has one. The
  browser still names it by the glyph, so `getByRole` by that title finds
  nothing. Give it an `aria-label`, or use
  `browser.locator('[title="Sign out"]')`.
- A `RegExp` name matches the browser's name, glyph included, so don't
  anchor it: `/Login/`.

## Semantic capture recovery

When the semantic reader times out, agent observations can recover with a
fresh viewport screenshot.

- The screenshot masks secure fields in every reachable frame, open and
  closed shadow roots included.
- The observation reports unavailable semantics and clears earlier node
  references.
- Recovery requires time left in the operation budget. `act` permits it;
  judgments require `vision: true` or `'only'`.
- Failed masking, cancellation, and hard engine errors still stop the
  observation.

## surfaceOf

Returns the live Playwright surface of a `web()` handle, for a
[custom executor](https://e2e.com/docs/executors#driving-the-page-yourself) that drives the page
itself.

```ts

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
export interface WebOptions {
  readonly browser?: BrowserName | BrowserProvider;
  readonly chromiumSandbox?: boolean;
  readonly viewport?: ViewportSize | null;
  readonly deviceScaleFactor?: number;
  readonly screencast?: WebScreencastOptions;
  readonly connect?: WebConnectOptions;
  readonly headers?: Readonly<Record<string, string>>;
  readonly basicAuth?: WebBasicAuth;
  readonly credentialOrigins?: readonly string[];
  readonly testIdAttribute?: string;
  readonly userAgent?: string;
  readonly locale?: string;
  readonly timezoneId?: string;
  readonly colorScheme?: WebMedia['colorScheme'];
  readonly reducedMotion?: WebMedia['reducedMotion'];
  readonly initScripts?: readonly WebInitScript[];
  readonly webmcp?: boolean;
}
```

### `Browser` interface

```ts
export interface Browser extends Expectable<BrowserExpectation> {
  readonly name: BrowserName;
  readonly version: string;
  goto(
    url: string,
    options?: {
      waitUntil?: 'load' | 'domcontentloaded' | 'networkidle';
      timeout?: number;
    },
  ): Promise<void>;
  reload(options?: ActionOptions): Promise<void>;
  back(options?: ActionOptions): Promise<void>;
  forward(options?: ActionOptions): Promise<void>;
  url(): Promise<string>;
  title(): Promise<string>;
  waitForURL(url: string | RegExp, options?: { timeout?: number }): Promise<void>;
  locator(selector: string): Locator;
  frameLocator(selector: string): FrameScreen;
  evaluate<T extends JsonValue>(fn: string | (() => T | Promise<T>)): Promise<T>;
  evaluate<T extends JsonValue, Arg extends JsonValue>(
    fn: string | ((arg: Arg) => T | Promise<T>),
    arg: Arg,
  ): Promise<T>;
  addInitScript(script: string | { path: string } | (() => unknown)): Promise<void>;
  addInitScript<Arg extends JsonValue>(script: (arg: Arg) => unknown, arg: Arg): Promise<void>;
  route(
    pattern: string | RegExp | RouteMatcher,
    handler: (route: WebRoute) => void | Promise<void>,
  ): Promise<void>;
  unroute(pattern: string | RegExp | RouteMatcher): Promise<void>;
  unrouteAll(): Promise<void>;
  waitForResponse(
    pattern: string | RegExp | RouteMatcher | ((response: PageResponse) => boolean | Promise<boolean>),
    options?: { timeout?: number },
  ): Promise<PageResponse>;
  waitForRequest(
    pattern: string | RegExp | RouteMatcher | ((request: WebRequest) => boolean | Promise<boolean>),
    options?: { timeout?: number },
  ): Promise<WebRequest>;
  cookies(urls?: string | readonly string[]): Promise<Cookie[]>;
  setCookies(cookies: readonly Cookie[]): Promise<void>;
  clearCookies(options?: CookieFilter): Promise<void>;
  setViewport(size: { width: number; height: number }): Promise<void>;
  emulateMedia(media: WebMedia): Promise<void>;
  setNetwork(state: 'online' | 'offline'): Promise<void>;
  onDialog(handler: DialogHandler): Promise<() => Promise<void>>;
  tabs(): readonly BrowserTab[];
  waitForPopup(trigger: () => Promise<void>, options?: { timeout?: number }): Promise<BrowserTab>;
  newTab(): Promise<BrowserTab>;
  waitForDownload(
    trigger: () => Promise<void>,
    options?: { timeout?: number },
  ): Promise<{ path: string; absolutePath: string; suggestedFilename: string }>;
  waitForDownloads(
    trigger: () => Promise<void>,
    options: { count: number; timeout?: number },
  ): Promise<readonly { path: string; absolutePath: string; suggestedFilename: string }[]>;
  readonly keyboard: {
    press(key: string): Promise<void>;
    down(key: string): Promise<void>;
    up(key: string): Promise<void>;
    type(text: string): Promise<void>;
  };
  readonly mouse: {
    move(x: number, y: number): Promise<void>;
    wheel(deltaX: number, deltaY: number): Promise<void>;
    down(): Promise<void>;
    up(): Promise<void>;
  };
  readonly webmcp: {
    tools(): Promise<readonly WebMcpTool[]>;
    callTool(name: string, input?: { readonly [key: string]: JsonValue } | null): Promise<JsonValue>;
  };
  readonly clock: BrowserClock;
}
```

### JsonValue

```ts
export type JsonPrimitive = string | number | boolean | null;

export type JsonValue =
  | JsonPrimitive
  | { readonly [key: string]: JsonValue }
  | readonly JsonValue[];
```

## Related

The [web guide](https://e2e.com/docs/web) covers starting the app, protected previews, and
viewports. The portable operations live on the [`app`](https://e2e.com/docs/reference/app)
fixture.
