Files
jaidev 003c18a4ee feat(web): match route and waitForResponse by method (#1924)
`browser.route`, `browser.unroute`, and `browser.waitForResponse` accept a `{ method, url }` RouteMatcher. The method is case-insensitive, `url` keeps the string or RegExp grammar, and a route narrowed to another method steps aside for older routes and the network. `unroute` removes routes registered with the same pattern, method included.
2026-11-21 14:45:01 +00:00

1216 lines
69 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: ブラウザ
description: ブラウザエンジン、そのオプション、エンジンが提供する browser フィクスチャ。
"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` はブラウザエンジンです。Playwright を通して Chromium、Firefox、WebKit を操作します。Web ターゲットには `web()` でエンジンを指定します。ブラウザ専用の操作には、このエンジンが提供する組み込みフィクスチャ `browser` を使います。
```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;
```
`browser` に型を付けるには、このパッケージから `test` をインポートします。
```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();
});
```
## リファレンス
### オプション
`web(options)` は、エンジンがアプリを操作する方法を設定します。アプリ自体の `url`、`environment`、`identity`、起動コマンドは、ターゲットの `app` に設定します。[テスト対象のアプリ](/reference/config#the-app-under-test)を参照してください。
```ts
web({ viewport: { width: 390, height: 844 }, locale: 'de-DE' });
```
| オプション | 型 | デフォルト |
| --- | --- | --- |
| [`browser`](#browser) | `BrowserName \| BrowserProvider` | `'chromium'` |
| [`chromiumSandbox`](#chromiumsandbox) | `boolean` | `true`(Linux では `false`) |
| [`viewport`](#viewport) | `ViewportSize \| null` | 1280 × 720 |
| [`screencast`](#screencast) | `WebScreencastOptions` | ビューポートのサイズ |
| [`connect`](#connect) | `WebConnectOptions` | ローカルで起動 |
| [`headers`](#headers) | `Record<string, string>` | - |
| [`basicAuth`](#basicauth) | `WebBasicAuth` | - |
| [`credentialOrigins`](#credentialorigins) | `string[]` | - |
| [`testIdAttribute`](#testidattribute) | `string` | `'data-testid'` |
| [`userAgent`](#useragent) | `string` | ブラウザ自身の値 |
| [`locale`](#locale) | `string` | ブラウザ自身の値 |
| [`timezoneId`](#timezoneid) | `string` | マシンの設定 |
| [`colorScheme`](#media-emulation) | `'light' \| 'dark' \| 'no-preference'` | ブラウザ自身の値 |
| [`reducedMotion`](#media-emulation) | `'reduce' \| 'no-preference'` | ブラウザ自身の値 |
| [`initScripts`](#init-scripts) | `WebInitScript[]` | - |
- `web()` ターゲットには `app.url` が必須です。デバイス用のキー(`bundleId`、`appPath`、`launchArguments`)は拒否します。`app.permissions` は、ブラウザが許可できる権限名に対する `'grant'` だけを受け付けます。[`permissions`](/reference/config#permissions) を参照してください。
- `app.url` を持つターゲットは `browser` ターゲットなので、`requires: ['browser']` で Web ターゲットを選択できます。
- JSDoc を含む完全な宣言は、型セクションの [`WebOptions`](#weboptions) にあります。
| エラー | 発生条件 |
| --- | --- |
| `INVALID_CONFIG` | `web()` が受け付けないオプション(`url` などアプリのキーも含む)、または `connect` や `basicAuth` 内に未知のキーがある場合。タイプミスと思われる場合は最も近い既知のキー(`viewprt` なら `viewport`)、それ以外はすべてのキーを示します。 |
| `INVALID_CONFIG` | [永続コンテキスト](#recovering-a-cdp-transport)(`connect.reconnectEndpoint`、または `scope: 'attempt'` のプロバイダー)で `headers`、`basicAuth`、`userAgent`、`locale`、`timezoneId` を指定した場合。 |
#### `browser`
起動するブラウザ、またはホスト型ブラウザをリースするプロバイダーです。
```ts
web({ browser: 'firefox' }); // default: 'chromium'
```
- `'chromium'`、`'firefox'`、`'webkit'` を指定できます。
- `BrowserProvider` を渡すと、代わりにホスト型ブラウザをリースします。実行中のワーカースロットごと、または試行ごとに 1 つです([`WebOptions`](#weboptions))。Chromium 自体でも、[Lightpanda](/integrations/lightpanda) や [Moli](/integrations/moli) のような別の CDP サーバーでも、エンジンは chromium として CDP 経由で操作します。
- `scope: 'attempt'` のプロバイダーは永続コンテキストを使います。[CDP 接続の復旧](#recovering-a-cdp-transport)に記載した制限が適用されます。
- [ホスト型ブラウザ](/browser#hosted-browsers)に `BrowserProvider` の契約と実装例があります。
| エラー | 発生条件 |
| --- | --- |
| `INVALID_CONFIG` | `browser: provider` と `connect` を併用した場合。 |
#### `chromiumSandbox`
ローカルで起動する Chromium を OS のサンドボックス付きで動かすかどうかです。
```ts
web({ chromiumSandbox: true }); // default: true on macOS and Windows, false on Linux
```
- サンドボックスは、エージェントが到達したページでのレンダラーの脆弱性悪用を封じ込める助けになります。[セキュリティ](/security)を参照してください。
- Linux のサンドボックスには非特権ユーザー名前空間が必要ですが、root、多くのコンテナ、Ubuntu 23.10 以降はこれをブロックします。許可しているホストでは `true` を設定してください。
- `connect` やプロバイダー経由のブラウザはそのホストが起動し、Firefox と WebKit にはこのオプションがないため、いずれもこの設定を読みません。
| エラー | 発生条件 |
| --- | --- |
| `INVALID_CONFIG` | 真偽値以外の値を渡した場合(設定の読み込み時)。 |
| `ENGINE_FAILURE` | サンドボックスが有効で、このホストでは起動できない場合。 |
#### `viewport`
各試行のページの初期ビューポートです。
```ts
web({ viewport: { width: 390, height: 844 } }); // default: { width: 1280, height: 720 }
```
`null` はサイズをエミュレートせず、ページがブラウザウィンドウ全体を使う指定です([`WebOptions`](#weboptions))。その場合も [`browser.setViewport`](#setviewport) で固定サイズにできます。
#### `screencast`
動画を記録する試行で、エンジン自身のスクリーンキャストをどう録画するかを設定します。
```ts
web({ screencast: { size: { width: 800, height: 450 }, quality: 60 } });
```
- `size` は整数のピクセル数で、各辺は 1 以上です。`quality` は整数です。
- どの試行を録画するかは、設定の [`video`](/reference/config#video) モードで決まります。
```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;
}
```
| エラー | 発生条件 |
| --- | --- |
| `INVALID_CONFIG` | 設定の読み込み時に、無効な `size` や `quality`、またはほかのキーがある場合。古い `web({ video })` という指定も拒否し、`screencast` を案内します。 |
#### `connect`
ローカルで起動せず、CDP 経由でリモートブラウザに接続します。
```ts
web({ connect: { cdpEndpoint: async () => 'ws://127.0.0.1:9222' } });
```
`reconnectEndpoint` を指定すると永続コンテキストを使います。[CDP 接続の復旧](#recovering-a-cdp-transport)を参照してください。
どちらのリゾルバーも、CDP ハンドシェイクを認証するために `CdpTarget` として `{ endpoint, headers }` を返せます。このヘッダーは、アプリに送る `web({ headers })` とは別です。
```ts
interface WebConnectOptions {
cdpEndpoint(signal: AbortSignal): string | CdpTarget | Promise<string | CdpTarget>;
reconnectEndpoint?(signal: AbortSignal): string | CdpTarget | Promise<string | CdpTarget>;
}
```
| エラー | 発生条件 |
| --- | --- |
| `INVALID_CONFIG` | 設定の読み込み時に、`connect` に `cdpEndpoint` がない、または文字列で指定されている場合。`connect` と `browser` プロバイダーの併用も該当します。 |
<a id="recovering-a-cdp-transport" />
##### CDP 接続の復旧
`connect.reconnectEndpoint(signal)` を指定すると、CDP 接続が切れた後に同じリモートブラウザへ再接続します。分離されたコンテキストを使う場合は省略してください。
リモートブラウザには次の要件があります。
- リトライを含め、各試行には `cdpEndpoint` から新しい専用のブラウザを取得する必要があります。1 つのブラウザを長期間共有してスイートを実行することはできません。
- リモートブラウザに存在してよいのは、デフォルトのコンテキストだけです。
- 試行終了時に、ホストがブラウザを削除する必要があります。エンジンのクリーンアップは接続を切り離すだけで、ホストのブラウザを終了しません。
- 試行の最初のページは、ブラウザ自身の最初のタブを `about:blank` に遷移させたものです。その隣に 2 つ目のタブは作りません。`app.restart` などで後から開くページは、新しいタブになります。
復旧は次のように行います。
- 切断後の次の操作で、その操作のタイムアウトと中断シグナルの範囲内で `reconnectEndpoint` を 1 回呼びます。リゾルバーは既存のブラウザのエンドポイントを返す必要があります。
- エンジンは永続的なデフォルトコンテキストの ID と、アクティブなタブのターゲット ID を確認します。デフォルトコンテキストの ID を公開しないブラウザは拒否します。アクティブなタブがない、またはコンテキストが異なる場合は、試行が失敗します。同じ URL でも代わりのタブを選ぶことはありません。ほかのタブもターゲット ID で探し、なくなったものは除外します。
- エンジンは各 CDP 接続を利用可能にする前に、機密フィールドのマスキングを設定します。Playwright のバージョンに互換性がない場合、画像を公開せず接続を失敗させます。
- 元のページのフレームには、閉じたシャドウ DOM を追跡するフックが残っている必要があります。既存の閉じたルートは、アプリを再読み込みしないと追跡を復旧できません。マスキング用のクエリは、追跡されていないドキュメントを拒否します。
- エンドポイントの解決、CDP 接続、準備、操作の送信は、1 つのタイムアウトを共有します。同時に待っている別の呼び出しをキャンセルしても、復旧を始めた操作はキャンセルしません。復旧を開始した操作がキャンセルされると、共有する復旧処理も失敗します。
| エラー | 発生条件 |
| --- | --- |
| `ENGINE_FAILURE` | 切断中に、閉じたシャドウ DOM のフックなしでドキュメントが読み込まれた場合。 |
| `OPERATION_TIMEOUT` | エンドポイントの解決、接続、準備、操作の送信で、共通のタイムアウトを使い切った場合。 |
| `CANCELLED` | 呼び出し元または試行がキャンセルされた場合。 |
復旧後の状態は次のとおりです。
- ページの未保存の状態、ストレージ、エージェントの台帳は維持します。ダイアログとルートのハンドラーを再登録します。
- 動画の記録を再開します。切断中に失われた部分は復元しません。
- 送信済みの操作は再実行しません。
- 古いノード参照は消去します。観測結果に基づく `tapAt` と `doubleTapAt`、観測のルートを対象とするスワイプ、フォーカス先へのエンジンのキーボード入力は、新しい観測を取得するまで再開できません。
- 復旧前に開始した観測やロケーターの読み取りは、接続の変更後に参照を公開できません。各試行が自身の接続と録画を所有するため、遅れて完了したクリーンアップが後の試行を変えることはありません。
- 決定論的な `browser.mouse` と `browser.keyboard` は、エージェントの観測なしで引き続き使えます。入力はテストコードが管理するため、操作前に `browser.evaluate` で現在の位置やフォーカスを確認できます。
- `surfaceOf(engine)` を使うコードは、復旧後にアクセサーを読み直す必要があります。保持していた Playwright オブジェクトは、切断済みの接続に属しています。
`scope: 'attempt'` の `browser` プロバイダーも、同じ永続コンテキストと制限を使います。リースの `cdpEndpoint` が試行のブラウザを用意し、`reconnectEndpoint`(なければ再び `cdpEndpoint`)がそこへ再接続します。プロバイダーの契約上、リースは新しいものなので、エンジンはコンテキストを過去の試行と比較しません。ホスト型サービスは同じスナップショットからブラウザを復元することがあり、新しいブラウザでも同じコンテキスト ID になるためです。
ファイルをまたいで 1 回のサインインを再利用するには、分離コンテキストを使い(`reconnectEndpoint` なし、プロバイダーの `scope: 'attempt'` なし)、[セットアップテストで 1 回サインイン](/authentication#reuse-authenticated-sessions)してください。認証状態は共有ブラウザではなく、保存済みセッションで引き継ぎます。
<Note>
永続コンテキストは `headers`、`basicAuth`、`userAgent`、`locale`、`timezoneId`([オプション](#options)を参照)、`app.clearState`、セッション状態の保存と復元に対応しません。`app.clearState` は `UNSUPPORTED_CAPABILITY` で失敗します。`app.restart` は引き続き使えます。
</Note>
#### `headers`
最初の宛先がアプリのオリジン(`app.url` のスキーム、ホスト、ポート)であるすべてのリクエストに加えるヘッダーです。最初の宛先が別ポート、サブドメイン、ほかのホストのリクエストには付きません。リダイレクトでは、転送先のオリジンにかかわらず、最初のリクエストのヘッダーを維持します。
```ts
web({ headers: { 'x-preview-token': process.env.PREVIEW_TOKEN ?? '' } });
```
- 許可されたオリジンへ向かう、[続行した](#route)リクエストにも付きます。
- `headers` と `basicAuth` は、[保護されたプレビュー](/web#protected-previews)にアクセスするための設定です。
- [リクエストの認証情報](/reference/security#request-credentials)を参照してください。
| エラー | 発生条件 |
| --- | --- |
| `INVALID_CONFIG` | `user-agent` と [`userAgent`](#useragent)、または `accept-language` と [`locale`](#locale) を併用した場合。 |
<Note>
`headers` はリクエストのルーティングを有効にするため、ブラウザの HTTP キャッシュが無効になり、Service Worker がブロックされます。
</Note>
#### `basicAuth`
HTTP Basic 認証の設定です。ブラウザは、アプリのオリジンからの `401` チャレンジにこの認証情報で応答します。ほかのオリジンには、[`credentialOrigins`](#credentialorigins) に列挙していない限り応答しません。
```ts
import { secrets } from 'e2e';
web({ basicAuth: { username: 'staging', password: secrets.get('staging-password') } });
```
`secrets.get(name)` のパスワードは各試行の開始時に解決し、設定済みのほかのシークレットと同じように秘匿します。それを Base64 化した `Authorization` ヘッダーの認証情報も同様です。
```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;
}
```
| エラー | 発生条件 |
| --- | --- |
| `INVALID_CONFIG` | ユーザー名に `:` があるか、未知のキーがある場合。 |
<Note>
WebKit は、スキームのデフォルトポート(`https://staging.example.com`)や IPv6 ホストを持つオリジンに、認証情報の送信先を限定できません。アプリのオリジンまたは `credentialOrigins` のいずれかが該当すると、Playwright のデフォルトと同じく、どのオリジンからの `401` にも応答します。
</Note>
<Warning>
シークレットの保護対象はテキストだけです。ページがパスワードを画面に表示した場合、スクリーンショットやモデルに送る画像ではマスキングされません([セキュリティルール](/reference/security#secrets-in-engine-options))。
</Warning>
#### `credentialOrigins`
アプリ自身のオリジン以外に、[`headers`](#headers) と [`basicAuth`](#basicauth) を受け取るオリジンを追加します。同じアクセス制限の背後にある別ホストの API などに使います。
```ts
web({
headers: { 'x-preview-token': process.env.PREVIEW_TOKEN ?? '' },
credentialOrigins: ['https://api.staging.example.com'],
});
```
各オリジンを正確に列挙してください。ホスト内の `*` やポート `0` は、どのリクエストにも一致しません。
| エラー | 発生条件 |
| --- | --- |
| `INVALID_CONFIG` | `headers` も `basicAuth` もない、エントリーがパス・クエリ・フラグメントのない `http:` または `https:` のオリジンではない、ホストに `*` がある、ポートが `0` の場合。 |
#### `testIdAttribute`
要素のテスト ID を持つ属性です。`testId` クエリ(`screen.getByTestId`)が解決し、`SemanticNode.testId` が報告する値になります。
```ts
web({ testIdAttribute: 'data-test' }); // default: 'data-testid'
```
#### `userAgent`
各試行のコンテキストが送信し、`navigator.userAgent` が返す `User-Agent` です。ユーザーエージェント文字列の識別子でテストモードに切り替えるアプリなどに使います。
```ts
web({ userAgent: 'Mozilla/5.0 e2e' }); // default: the browser's own
```
#### `locale`
各試行のコンテキストが使うロケールを、BCP 47 タグで指定します。`navigator.language`、`Intl` の書式、`Accept-Language` ヘッダーに反映されます。
```ts
web({ locale: 'de-DE' }); // default: the browser's own
```
#### `timezoneId`
各試行のコンテキストが使う IANA タイムゾーンです。`Date` と `Intl` がローカル時刻を解決する基準になります。
```ts
web({ timezoneId: 'Europe/Berlin' }); // default: the machine's
```
#### メディアのエミュレーション
`web({ colorScheme, reducedMotion })` は、Playwright の同名のコンテキストオプションと同じく、各試行のすべてのページが報告するメディア特性を設定します。`browser.emulateMedia(media)` は、1 回の試行について変更します。
```ts
web({ colorScheme: 'dark', reducedMotion: 'reduce' }); // default: the browser's own
await browser.emulateMedia({ colorScheme: 'light' });
```
- ページの `@media` ルールと `matchMedia` は、最初の描画からこの値を読みます。
- 永続コンテキストでも指定できます。エンジンが、開く各ページに設定します。
- `emulateMedia` は、開いているすべてのタブと今後開くタブに、試行の残りの期間適用します。`app.restart()` と `app.clearState()` をまたいでも維持します。
- 最初のページ遷移前にも使えるため、次の `app.open` はその値で読み込みます。
- 省略した特性は現在の値を維持します。
- アプリ自身が開くタブには、永続コンテキストでも、タブが現れた時点でテストによる変更を適用します。そのため、読み込み時のスクリプトは設定ファイルの値を読むことがあります。
```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';
}
```
| エラー | 発生条件 |
| --- | --- |
| `INVALID_CONFIG` | `web()` で `WebMedia` にない特性や値を指定した場合。 |
| `INVALID_ARGUMENT` | `emulateMedia` で `WebMedia` にない特性や値を指定した場合。 |
#### 初期化スクリプト
初期化スクリプトは、すべてのタブとフレームの各ドキュメントで、ページ自身のスクリプトより先に実行します。`web({ initScripts })` はすべてのテストに適用し、`browser.addInitScript` はそのテストの残りの期間に追加します。
```ts
await browser.addInitScript((value) => { Math.random = () => value; }, 0.5);
await app.open('/raffle');
```
- 関数はテストの変数をクロージャーで参照できません。代わりに JSON の `arg` を渡してください。
- ページが開いた後に追加したスクリプトは、次の遷移または再読み込みから実行します。
- `browser.addInitScript` は同じ 3 形式に加え、関数と JSON の `arg` を受け付けます。オーバーロードは [`Browser`](#browser-interface) にあります。
```ts
/** JavaScript source, a file relative to the project root, or a function. */
export type WebInitScript = string | { readonly path: string } | (() => unknown);
```
### browser フィクスチャ
`browser` はブラウザ全体を表し、1 つのアクティブなタブを表示します。
- ページを読む操作やアクションは、アクティブなタブに対して行います。`goto`、`reload`、`back`、`forward`、`url`、`title`、`waitForURL`、`locator`、`frameLocator`、`evaluate`、`waitForResponse`、`waitForDownload`、`keyboard`、`mouse`、`expect(browser)` のマッチャー、すべての `screen` クエリが対象です。
- ブラウザ全体に属する操作は、すべてのタブに適用します。`cookies`、`setCookies`、`clearCookies`、`route`、`unroute`、`unrouteAll`、`onDialog`、`addInitScript` が対象です。
- `setViewport` は、アクティブなタブとそれ以降に開くタブのサイズを設定します。
- [`emulateMedia`](#media-emulation) は、すべての既存タブと今後のタブのメディア特性を変更します。
- `target="_blank"` のリンクや `window.open` からアプリが開くタブは、バックグラウンドで開きます。`waitForPopup` または `activate` で別のタブをアクティブにするまで、現在のタブは変わりません。[タブ](#tabs)を参照してください。
- `locator` と `frameLocator` を除くすべての `browser` 呼び出しは、`browser.<method>` ステップとして記録します。この 2 つはページに触れずにロケーターを作り、それを使うアクションやアサーションがステップになります。
- 相対 URL はターゲットの `app.url` を基準に解決します。なければ `APP_URL_REQUIRED` です。
- ほかのプラットフォームでも動くスイートでは、`requires: ['browser']` を宣言してください。
- `expect(browser)` は、エンジンが付ける `BrowserExpectation` を返します。`toHaveURL`、`toHaveTitle`、`toHaveClass` を使えます。[browser のマッチャー](/reference/expect#browser-matchers)を参照してください。
| メンバー | 戻り値 |
| --- | --- |
| [`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 }` |
各メンバーの時間上限は[設定](/reference/config)で決まります。
- `goto`、`reload`、`back`、`forward`: `app.open()` と同じ [`timeout`](/reference/config#timeout)。
- `waitForURL`: [`assertionTimeout`](/reference/config#assertiontimeout)。
- それ以外: [`actionTimeout`](/reference/config#actiontimeout)。`locator` と `frameLocator` はページに触れず、時間上限を使いません。
`goto`、`reload`、`back`、`forward`、`waitForResponse`、`waitForPopup`、`waitForDownload`、`waitForDownloads` は、`{ timeout }` で上書きできます。ただし、テストの期限(`afterEach` 内では `cleanupTimeout`)が上限で、`0` はその期限まで待ちます。`url`、`title`、`evaluate`、`addInitScript`、`route`、`unroute`、`unrouteAll`、`cookies`、`setCookies`、`clearCookies`、`setViewport`、`emulateMedia`、`onDialog`、`newTab`、`BrowserTab` のメソッド、`keyboard.*`、`mouse.*` に上書きオプションはありません。
#### `goto`
アクティブなタブを指定の URL に遷移させます。
```ts
await browser.goto('/dashboard', { waitUntil: 'networkidle' }); // default: 'load'
```
`waitUntil` は `'load'`、`'domcontentloaded'`、`'networkidle'` のいずれかです。
| エラー | 発生条件 |
| --- | --- |
| `POLICY_DENIED` | URL のスキームが `http:` または `https:` 以外の場合。`about:blank` は許可されます。 |
| `APP_URL_REQUIRED` | `app.url` のないターゲットで相対 URL を指定した場合。 |
| `ACTION_FAILED` | ページ遷移が失敗した場合。 |
#### `reload`、`back`、`forward`
`reload` は現在のドキュメントを再読み込みします。`back` と `forward` はブラウザ履歴を 1 つ戻る、または進む操作です。いずれもドキュメントの読み込みを待ちます。戻る・進むキャッシュからの復元では、読み込み済みのドキュメントを再利用することがあります。アプリの内容を待つには、ロケーターとアサーションを使ってください。
```ts
await browser.reload();
await browser.back({ timeout: 10_000 });
```
| エラー | 発生条件 |
| --- | --- |
| `ACTION_FAILED` | ページ遷移が失敗した場合。 |
#### `url`、`title`
アクティブなタブの現在の URL とタイトルを返します。
```ts
const url = await browser.url();
const title = await browser.title();
```
#### `waitForURL`
現在の URL が一致するまで待ちます。開始から 0、20、50 ms、その後は 100 ms ごとに URL を読みます。`expect(browser).toHaveURL` と同じポーリングです。
```ts
await browser.waitForURL(/\/orders\/\d+$/, { timeout: 15_000 });
```
- 相対文字列はベース URL を基準に解決し、正規化後に完全一致で比較します。
- `RegExp` は URL 全体に適用します。
| エラー | 発生条件 |
| --- | --- |
| `INVALID_ARGUMENT` | パターンが文字列や `RegExp` ではない場合(述語関数など)、または Playwright の `waitUntil` など、`timeout` 以外のオプションがある場合。 |
| `ASSERTION_FAILED` | タイムアウトまでに URL が一致しなかった場合。 |
#### `locator`
Playwright のセレクターから、Web 専用のロケーターを作ります。
```ts
const conditions = browser.locator(
'[data-testid="row"] >> nth=2 >> [data-testid="conditions"] > div',
);
```
- セレクターはデフォルトで CSS です。`xpath=` または先頭の `//` で XPath になり、`>>` で連結できます。例では、この連結を使って CSS の検索範囲を 1 行に絞っています。
- 別の要素を内包する要素には、`filter({ has })` を使います。
| エラー | 発生条件 |
| --- | --- |
| `INVALID_LOCATOR` | 空のセレクター、または最後の部分より前の `*` キャプチャ(`*css=article >> text=Hello`)。 |
<Note>
すべての `screen` クエリは、スコープとその下にページが作った閉じたシャドウルートを検索します。ロール、名前、テキスト、ラベル、属性の照合には Playwright のルールを使い、各ノードは 1 回だけ取得します。観測ツリーに載る閉じたルート内のコントロールも解決でき、アクションと読み取りを行えます。`locator`、`frameLocator`、`filter({ hasText })` は Playwright と同じ範囲だけを検索し、閉じたルートには入りません。詳細は[ブラウザガイド](/browser#shadow-dom)を参照してください。
</Note>
#### `frameLocator`
1 つの iframe 内に、screen クエリのスコープを作ります。
```ts
const payment = browser.frameLocator('#payment-frame');
await payment.getByLabel('Card number').fill('4242424242424242');
```
`FrameScreen` を返します。これは、クエリがフレーム内の要素を返す `Screen` です。フレームの `locator` は、コントロールにアクセシブルな名前、ラベル、プレースホルダー、テスト ID がない場合にだけ使ってください。該当する状況は[ブラウザガイド](/browser#reach-into-an-iframe)で説明しています。
```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;
}
```
ページとフレーム内で、エラーは同じです。
| エラー | 発生条件 |
| --- | --- |
| `INVALID_LOCATOR` | ここ、またはフレームの `locator` に空のセレクターを渡した場合。 |
| `LOCATOR_NOT_FOUND` | 一致するフレームがない場合。 |
| `LOCATOR_AMBIGUOUS` | 複数のフレームが一致した場合。 |
#### `evaluate`
信頼できるテストコードをページ内で評価し、結果を返します。
```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');
```
- 関数はページ内で動き、テストの変数にはアクセスできません。e2e は関数のソースをシリアライズしてページに埋め込むため、本体の外にある値をクロージャーで参照しないでください。本体内で宣言したヘルパーは使えます。外部の値は `arg` で渡します。
- 文字列は文の列ではなく、1 つの式として評価します。結果が関数なら `arg` を渡して呼び、それ以外ならその値を結果にします。
- どちらも Promise を返した場合は await します。
| エラー | 発生条件 |
| --- | --- |
| `INVALID_ARGUMENT` | `arg` または戻り値が [`JsonValue`](#jsonvalue) ではない場合。`DOMRect` や要素などのクラスインスタンスも該当します。`rect.toJSON()` または必要なフィールドを返してください。 |
| `EVALUATE_FAILED` | 評価したコードが例外をスローした場合、またはページがエンジンに必要な `Map` などの JavaScript 組み込みを置き換えた場合。エラーにメッセージを含めます。 |
| `ACTION_FAILED` | Playwright のタイムアウト。 |
| `ENGINE_FAILURE` | ページが閉じたか、コンテキストが失われた場合。 |
#### `route`
試行の範囲で有効なネットワークルートを追加します。
```ts
await browser.route('**/api/quote', async (route) => {
await route.fulfill({ json: { cents: 4200 } });
});
await browser.route({ method: 'POST', url: '**/api/orders' }, async (route) => {
await route.fulfill({ json: { id: 7 } });
});
```
`route.fetch()` は、ルートの処理方法を決定せずに、本来の送信先からの `{ url, status, headers, body(), text(), json() }` を返します。対象オリジンが設定済みヘッダーの送信対象なら、そのヘッダーを使います。アクションのタイムアウトが適用されます。ページ遷移のルールを超える可能性があるため、リダイレクトには従いません。
- パターンは文字列または `RegExp` で、どちらも URL 全体と照合します。文字列の `*` はパスの 1 セグメント内、`**` は `/` をまたいで一致し、`?` は任意の 1 文字、`\` は次の文字をエスケープします。`unroute` と `waitForResponse` も同じパターンを使います。
- `{ method, url }` を渡すと、HTTP メソッドも 1 つに絞り込めます。`method` は大文字と小文字を区別せず、`url` は上記の文字列または `RegExp` の構文を使い、`unroute` と `waitForResponse` も同じ形式を受け付けます。
- メソッドが一致しないルートは、それより前に登録したルート、次にネットワークへ処理を渡します。URL が一致しなかった場合と同じ扱いです。
- メソッドパターンはそのメソッドだけに一致します。`GET` のルートは `HEAD` に応答しません。
- ルートは `app.restart()`、`app.clearState()`、セッションの復元をまたいでも残ります。
- 新しく登録したルートから順に実行します。
- ハンドラーは `fulfill`、`continue`、`fallback`、`abort` のいずれかで、必ず 1 回だけ処理を決定します。それぞれの説明は下の `WebRoute` にあります。
- `continue` の URL は `goto` と同じルールで検証します。`continue` で `undefined` にしたヘッダーは、リダイレクト時も削除します。
- `fulfill` の本文は文字列またはバイト列(`Buffer`、`Uint8Array`)で、そのまま送ります。
- 複数の Cookie を設定するには、`route.fetch()` のヘッダーと同じく、1 つの `set-cookie` ヘッダー内で `\n` で連結します。それ以外のヘッダー内の改行は拒否します。
- ハンドラーが例外をスローすると(リクエストへの `expect` が失敗した場合など)、次のステップをそのエラーで失敗させます。後続のステップがなければ、試行の終了時に失敗させます。リクエストが中断された `goto` など、ハンドラーの失敗によって失敗したステップには、ハンドラーのエラーを使います。ハンドラーが意図的にリクエストを中断した `goto` は `ACTION_FAILED` になります。その時点でまだ動いているハンドラーには、完了までクリーンアップの時間を与えます。その時間を過ぎてからスローされた例外は破棄します。
| エラー | 発生条件 |
| --- | --- |
| `INVALID_ARGUMENT` | パターンが文字列、`RegExp`、`{ method, url }` のいずれでもない場合。`{ method, url }` パターンにキーの不足または余分なキーがある場合、`method` が HTTP メソッドでない場合、`url` が文字列でも `RegExp` でもない場合。また、処理の決定で受け付けないオプション(Playwright の `abort(errorCode)`、`bodyy` のような誤記したキー)がある場合は、リクエストを中断して次のステップを失敗させます。 |
| `ACTION_FAILED` | ハンドラーが処理を 2 回決定したか、決定しなかった場合。 |
| `POLICY_DENIED` | `continue` の URL が禁止スキームを使う場合。 |
| `CLEANUP_TIMEOUT` | ハンドラーがクリーンアップの時間を超えた場合。試行を失敗させます。 |
```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;
}
/** A URL pattern narrowed to one HTTP method. */
export interface RouteMatcher {
/** The HTTP method to match, case-insensitive: `'POST'` and `'post'` are the same. */
readonly method: string;
/**
* The URL pattern: a string using the same grammar as a plain `route`
* pattern, or a `RegExp`. `route` and `waitForResponse` match requests
* against it; `unroute` compares it structurally.
*/
readonly url: string | RegExp;
}
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`
登録時と同じパターンのルートを削除します。文字列は同じ文字列、`RegExp` は同じ source と flags、`{ method, url }` は同じメソッドと URL である必要があります。URL のマッチングは行わないため、`unroute('**/api/*')` は `'**/api/orders'` で登録したルートを削除しません。
```ts
await browser.unroute('**/api/quote');
await browser.unroute({ method: 'POST', url: '**/api/orders' });
```
| エラー | 発生条件 |
| --- | --- |
| `INVALID_ARGUMENT` | パターンが文字列、`RegExp`、`{ method, url }` のいずれでもない場合。`{ method, url }` パターンにキーの不足または余分なキーがある場合、`method` が HTTP メソッドでない場合、`url` が文字列でも `RegExp` でもない場合。 |
#### `unrouteAll`
browser フィクスチャが登録したすべてのルートを削除します。設定済みのヘッダーは保持します。
```ts
await browser.unrouteAll();
```
#### `waitForResponse`
[`route`](#route) と同じパターン構文で、一致するレスポンスを待ちます。
```ts
const response = await browser.waitForResponse('**/api/orders');
expect(response.status).toBe(201);
```
```ts
const created = browser.waitForResponse({ method: 'POST', url: '**/api/orders' });
await screen.getByRole('button', 'Place order').tap();
expect((await created).status).toBe(201);
```
- `{ method, url }` パターンは、そのメソッドへのレスポンスだけに一致します。別のメソッドへのレスポンスは対象外です。
- 期限が制限するのは、一致するレスポンスを待つ時間です。ヘッダーが届いた時点で解決します。
- `body()`、`text()`、`json()` は、それぞれ独自の時間上限で本文を待ちます。`config.actionTimeout` を使い、テストの期限を上限とします。
- `url`、`status`、`headers` は常に読めます。
- 本文が実際に空なら、`body()` は空の `Buffer`、`text()` は `''` を返し、`json()` は拒否します。
| エラー | 発生条件 |
| --- | --- |
| `INVALID_ARGUMENT` | パターンが文字列、`RegExp`、`{ method, url }` のいずれでもない場合。`{ method, url }` パターンにキーの不足または余分なキーがある場合、`method` が HTTP メソッドでない場合、`url` が文字列でも `RegExp` でもない場合。 |
| `ACTION_FAILED` | 期限内に一致するレスポンスがなかった場合。`body()`、`text()`、`json()` では、期限時点でも本文の受信が続いている場合や、ブラウザが本文を読めなかった場合も、空文字列の代わりにこのエラーになります。後者には、宣言された `Content-Length` に達する前の接続リセット、ページが中断したリクエスト、ブラウザが本文を保持しないリダイレクトが含まれます。 |
```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`
現在のコンテキストから参照できる Cookie を返します。
```ts
const cookies = await browser.cookies();
```
#### `setCookies`
すべての Cookie を検証してから設定します。
```ts
await browser.setCookies([{ url: 'http://localhost:3000', name: 'tz', value: 'UTC' }]);
```
- 相対 `url` は、`goto` と同じくベース URL を基準に解決します。
- `domain` 形式では、スキームはベース URL に従い、先頭の `.` は除去します。
| エラー | 発生条件 |
| --- | --- |
| `POLICY_DENIED` | 対象をパースできないか、禁止スキームの場合。何も設定しません。 |
```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? })` は、指定したすべてのフィルターに一致する Cookie を削除します。文字列は完全一致、RegExp はそのフィールドに適用します。オプションなしでは、すべての Cookie を削除します。ほかのストレージは残ります。
```ts
await browser.clearCookies({ name: /^session/, path: '/' });
```
```ts
export interface CookieFilter {
name?: string | RegExp;
domain?: string | RegExp;
path?: string | RegExp;
}
```
#### `setViewport`
ビューポートのサイズを設定し、新しいサイズをレポートに記録します。
```ts
await browser.setViewport({ width: 390, height: 844 });
await app.open('/');
```
- Playwright の `setViewportSize` と同じく、最初のページ遷移前にも使えます。次の `app.open` はそのサイズで読み込むため、スマートフォンサイズのテストが先にデスクトップレイアウトを描画することはありません。
- サイズは、`app.restart()` と `app.clearState()` をまたいで、試行の残りの期間維持します。
#### `onDialog`
試行内で有効なネイティブダイアログのハンドラーを登録し、登録解除の関数を返します。
```ts
const off = await browser.onDialog('accept');
await screen.getByRole('button', 'Delete').tap();
await off();
```
- ハンドラーは `'accept'`、`'dismiss'`、または `Dialog` を受け取る関数です。
- 関数ハンドラーは `accept` または `dismiss` を呼ぶ必要があります。どちらも呼ばなければ、未処理のダイアログと同じく閉じます。
- ハンドラーが例外をスローすると、次のステップをそのエラーで失敗させます。後続のステップがなければ、試行の終了時に失敗させます。応答前にスローした場合は、ダイアログを閉じます。
エラーは `onDialog` ではなく、次のステップに現れます。
| エラー | 発生条件 |
| --- | --- |
| `APP_NOT_OPEN` | 関数ハンドラーがどちらの応答もしなかったか、ダイアログを処理するハンドラーがなかった場合。 |
| `ASSERTION_FAILED` | ハンドラーの `expect` が失敗した場合。 |
| `ENGINE_FAILURE` | ハンドラーが未分類のエラーをスローした場合。 |
```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>);
```
#### タブ
`target="_blank"` のリンクや `window.open` からアプリが開くタブは、バックグラウンドで開きます。アクティブなタブは変わらず、`screen`、`expect`、`browser` のページ操作は引き続きそのタブを対象にします。`waitForPopup` は、トリガーが開いたタブをアクティブにします。アクティブなタブが閉じると、それを開いたタブに戻ります。そのタブもなければ、開いているタブのうち最後にアクティブだったものに戻ります。
```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)` はトリガーを実行し、開いたタブがアクティブになると、そのタブを返します。待機開始後に最初に現れたタブを取得します。以前の操作で開かれ、今になってページが読み込まれたタブが対象になることもあります。
- `tabs()` は開いた順にタブを返し、試行中は同じタブに同じ `BrowserTab` を返します。最初のページを読み込んだ時点で一覧に加わるため、1 つの操作で 2 タブが開くと、ページの読み込み順に並びます。ページを持たないタブは一覧に載りません。ダウンロード、`mailto:` アドレス、内容のないレスポンスへ向かう `target="_blank"` リンクなどが該当します。
- `tab.activate()` は、ほかのタブを閉じずにそのタブをアクティブにします。`tab.close()` はタブを閉じ、アクティブだった場合は次のタブがアクティブになるまで待ちます。
- `newTab()` は、同じ Cookie とストレージを持つ同一ブラウザコンテキストに空のタブを開き、アクティブにします。`goto` で遷移してください。
- Chromium では、読み込み前に開き元が閉じたタブも一覧に載ります。テストが `surfaceOf(engine)` で開いたページは載りません。
- スクリーンキャストはアクティブなタブを記録し、切り替わるごとに動画セグメントを分けます。自分自身を閉じるタブは、録画を保存する前にページが閉じるため、セグメントを残しません。プロバイダー自身の録画は、すべてのタブを対象にします。
```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>;
}
```
| エラー | 発生条件 |
| --- | --- |
| `ACTION_FAILED` | `waitForPopup`: 時間内にタブが開かなかった場合。トリガーが時間内に解決した場合は `no tab opened within <n>ms; the trigger resolved after <m>ms`、タブが最初のページをまだ読み込み中なら `the tab the app opened did not load <url> within <n>ms` になります。`activate`: タブが閉じている場合。 |
#### `waitForDownload`
トリガーを実行し、それが開始するダウンロードを待ちます。
```ts
const file = await browser.waitForDownload(() =>
screen.getByRole('link', 'Export CSV').tap(),
);
```
- ファイルを `download` アーティファクトとして登録し、相対 `path`、ランナー側の `absolutePath`、`suggestedFilename` を返します。
- ホスト型ブラウザの場合も、ファイル API で内容を調べるには `absolutePath` を使います。
- ホスト型ブラウザでは、プロバイダーの [`downloads`](/browser#downloads-on-the-provider) を通してファイルを取得します。
- 待機時間には、トリガー自体の実行時間も含みます。
| エラー | 発生条件 |
| --- | --- |
| `ACTION_FAILED` | 時間内にダウンロードが完了しなかった場合。トリガーは時間内に解決したもののダウンロードを開始しなかった場合は、`no download started within <n>ms; the trigger resolved after <m>ms` になります。 |
タイムアウト時にトリガーがまだ動いていれば、ステップのタイムアウトになります。トリガーが例外をスローした場合は、そのエラーで失敗します。
#### `waitForDownloads`
`waitForDownloads(trigger, { count })` はトリガーを 1 回呼び、同じタイムアウトの範囲内で、開始順に `count` 個のファイルを返します。それぞれが独立したアーティファクトです。時間内に開始した数が足りなければ、期待数と実際の数をエラーに表示します。余分なダウンロードは無視します。
#### `keyboard`
要素を指定せず、ページ全体に対してキーボード入力を送ります。入力はフォーカスのある要素に届きます。
```ts
await browser.keyboard.press('Escape');
await browser.keyboard.type('hello');
```
- `type(text)` が入力するのは通常のテキストだけで、`Secret` は使えません。
- 対象がある場合は、`locator.press` と `locator.fill` を優先してください。
- 各メソッドの説明は [`Browser`](#browser-interface) にあります。
#### `mouse`
エージェントの観測とは独立して、テストコードからビューポートの座標でポインター入力を行います。
```ts
await browser.mouse.move(120, 240);
await browser.mouse.down();
await browser.mouse.move(320, 240);
await browser.mouse.up();
```
`wheel` を含む各メソッドの説明は [`Browser`](#browser-interface) にあります。
## ブラウザのインストール
パッケージは `playwright-core` を完全一致のバージョンに固定しているため、エンジンは常に検証済みの Playwright で動きます。アプリ自身が Playwright に依存する場合は、別のコピーを保持します。バージョンが一致するときだけ、ブラウザのキャッシュを共有します。
ブラウザがなければ、実行時間の計測開始前に、1 回の実行につき 1 回ダウンロードします。CI やコンテナイメージで独立した手順としてインストールするには、パッケージのコマンドを使ってください。エンジンが固定している 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>
- `chromium`、`firefox`、`webkit` を指定できます。省略すると `chromium` をインストールします。
- `--with-deps` は、Linux でブラウザが必要とするシステムライブラリもインストールします。
- コマンドはインストーラーの終了コードで終了します。
## セマンティック情報の取得失敗からの復旧
セマンティック情報の読み取りがタイムアウトすると、エージェントの観測は、新しいビューポートのスクリーンショットを使って続行できる場合があります。
- Playwright は、開いたシャドウルートと閉じたシャドウルートを含む、到達可能なすべてのフレームで機密フィールドのマスキングを再確認します。すべての確認が成功する必要があります。
- 観測はセマンティック情報が利用不能であることを示し、それ以前のノード参照を消去します。
- 復旧には、操作の残り時間とランナーの許可が必要です。`act` は許可します。判定では `vision: true` または `'only'` が必要です。
- マスキングの失敗、キャンセル、回復不能なエンジンエラーでは、観測を停止します。
フォールバックが許可されている場合、読み取り処理は残りの観測時間の 4 分の 1(最大 2 秒)をスクリーンショット用に確保します。期限には、ページの走査、メタデータと要素の読み戻し、入れ子のフレームがすべて含まれます。
セマンティックメタデータは、シリアライズの負荷を減らすため、1 つの JSON 文字列として Playwright 接続を通過します。走査した要素はドキュメントごとのページ内配列に保持し、アクションが初めてノードを使うときに、その配列からハンドルを作ります。参照は走査時に読んだ要素を指し続け、後から同じ位置にある別の要素を指すことはありません。ページが `JSON.stringify` を置き換えたり、オブジェクトや配列のプロトタイプに `toJSON` を加えたりしている場合は、構造化したデータとして転送します。クリーンアップは、応答の止まったプロトコル通信を待ちません。待機を打ち切られた読み取り処理が、ノード ID を再利用したり、新しい観測に古い参照を上書きしたりすることはできません。
## surfaceOf
ページを自ら操作する[カスタムエグゼキューター](/executors#driving-the-page-yourself)向けに、`web()` ハンドルが持つ稼働中の Playwright オブジェクトへのアクセスを返します。
```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
```
- 別のパッケージのハンドルには `undefined` を返します。
- Playwright の直接呼び出しは、ステップとして記録しません。
- [CDP の復旧](#recovering-a-cdp-transport)後は、アクセサーを読み直してください。
| エラー | 発生条件 |
| --- | --- |
| `INVALID_STATE` | アクティブな試行の外でアクセサーを呼び出した場合。 |
## 型
設定用ヘルパーやフィクスチャに型を付けるために、次の型をエクスポートします。
`WebEngine`、`WebOptions`、`WebMedia`、`WebScreencastOptions`、`WebConnectOptions`、
`WebBasicAuth`、`WebInitScript`、`BrowserName`、`BrowserProvider`、
`BrowserProviderScope`、`BrowserRequest`、`BrowserLease`、
`BrowserReleaseContext`、`BrowserProviderDownloads`、
`BrowserDownloadContext`、`PlaywrightLiveSurface`、`Browser`、`FrameScreen`、
`BrowserExpectation`、`WebRoute`、`RouteFulfillResponse`、
`RouteContinueOverrides`、`RouteMatcher`、`WebResponse`、`Cookie`、`CookieFields`、
`CookieFilter`、`Dialog`、`DialogHandler`。
実行時のエクスポートは `web`、[`surfaceOf`](#surfaceof)、および `browser` フィクスチャの型を持つ `test`、`describe`、`beforeEach`、`afterEach`、`beforeAll`、`afterAll` です。
### `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` インターフェース
```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, optionally narrowed to one HTTP method. */
route(
pattern: string | RegExp | RouteMatcher,
handler: (route: WebRoute) => void | Promise<void>,
): Promise<void>;
/**
* Removes the routes registered with the same pattern: the same string or
* `RegExp` source and flags, and the same method for a `{ method, url }`
* pattern. It does not URL-match registered routes.
*/
unroute(pattern: string | RegExp | RouteMatcher): Promise<void>;
/** Removes all routes registered by this browser fixture, preserving the configured headers. */
unrouteAll(): Promise<void>;
/** Waits for a matching response, optionally narrowed to one HTTP method. */
waitForResponse(
pattern: string | RegExp | RouteMatcher,
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[];
```
## 関連項目
[ブラウザガイド](/browser)では、これらのメンバーを使う実践例と[ホスト型ブラウザ](/browser#hosted-browsers)を説明しています。プラットフォーム共通の操作は [`app`](/reference/app) フィクスチャにあります。