Playwright Frame と新規ウィンドウ
この章では、iframe、ダイアログボックス、新規タブ、そして Playwright のイベントシステムの処理方法を紹介します。
iframe 操作
Playwright では、frameLocator()を使用して iframe 内の要素を特定・操作します。
page.frameLocator() で iframe を特定する
例
test('iframe 内の要素を操作', async ({ page }) => {
await page.goto('https://www.example.com/iframe-demo');
// iframe を特定し、その中で要素を特定する
const iframe = page.frameLocator('#my-iframe');
// iframe 内で要素を操作する
await iframe.getByRole('button', { name: '送信' }).click();
await iframe.getByLabel('ユーザー名').fill('サンプル_user');
// iframe 内でアサーションする
await expect(iframe.getByText('操作成功')).toBeVisible();
});
await page.goto('https://www.example.com/iframe-demo');
// iframe を特定し、その中で要素を特定する
const iframe = page.frameLocator('#my-iframe');
// iframe 内で要素を操作する
await iframe.getByRole('button', { name: '送信' }).click();
await iframe.getByLabel('ユーザー名').fill('サンプル_user');
// iframe 内でアサーションする
await expect(iframe.getByText('操作成功')).toBeVisible();
});
すべての Frame を取得
例
// ページ内のすべての frame(メイン frame と iframe を含む)を取得
const frames = page.frames();
console.log('ページは全部で', frames.length, '個の frame');
frames.forEach(frame => {
console.log('Frame:', frame.name(), frame.url());
});
const frames = page.frames();
console.log('ページは全部で', frames.length, '個の frame');
frames.forEach(frame => {
console.log('Frame:', frame.name(), frame.url());
});
ネストされた iframe
Playwright のframeLocator()チェーン呼び出しに対応しており、ネストされた iframe の奥深くまでアクセスできます。
例
// ネストされた iframe:外側 → 内側 → 要素
const innerButton = page
.frameLocator('#outer-frame')
.frameLocator('#inner-frame')
.getByRole('button', { name: '確認' });
await innerButton.click();
const innerButton = page
.frameLocator('#outer-frame')
.frameLocator('#inner-frame')
.getByRole('button', { name: '確認' });
await innerButton.click();
ダイアログ処理(Dialogs)
Playwright はブラウザのネイティブダイアログ(alert、confirm、prompt)に対してデフォルトの処理戦略を持っています。
デフォルトの動作
Playwright はデフォルトで自動的に閉じるすべてのダイアログ:
| ダイアログの種類 | デフォルトの動作 |
|---|---|
alert() | 自動確認(閉じる) |
confirm() | 自動確認(true を返す) |
prompt() | 自動確認(空文字列を返す) |
ダイアログのカスタム処理
を使用してpage.on('dialog')ダイアログをインターセプトしてカスタム処理できます。
例
test('ダイアログのカスタム処理', async ({ page }) => {
// ダイアログをトリガーする前にリスナーを登録
page.on('dialog', async dialog => {
console.log('ダイアログの種類:', dialog.type());
console.log('ダイアログのメッセージ:', dialog.message());
if (dialog.type() === 'confirm') {
// 確認ダイアログをキャンセル
await dialog.dismiss();
} else if (dialog.type() === 'prompt') {
// カスタム内容を入力
await dialog.accept('サンプル が入力した内容');
} else {
// その他のタイプは直接確認
await dialog.accept();
}
});
// ダイアログをトリガーする操作
await page.getByRole('button', { name: '削除' }).click();
});
// ダイアログをトリガーする前にリスナーを登録
page.on('dialog', async dialog => {
console.log('ダイアログの種類:', dialog.type());
console.log('ダイアログのメッセージ:', dialog.message());
if (dialog.type() === 'confirm') {
// 確認ダイアログをキャンセル
await dialog.dismiss();
} else if (dialog.type() === 'prompt') {
// カスタム内容を入力
await dialog.accept('サンプル が入力した内容');
} else {
// その他のタイプは直接確認
await dialog.accept();
}
});
// ダイアログをトリガーする操作
await page.getByRole('button', { name: '削除' }).click();
});
Dialog オブジェクトのメソッド
| メソッド | 説明 |
|---|---|
dialog.accept(promptText?) | ダイアログを確認(prompt の場合は入力テキストを渡せます) |
dialog.dismiss() | ダイアログをキャンセル |
dialog.message() | ダイアログのメッセージを取得 |
dialog.type() | ダイアログの種類を取得:'alert' | 'confirm' | 'prompt' | 'beforeunload' |
新規ウィンドウと新規タブ
リンクやボタンをクリックして新しいタブを開くとき、Playwright は新しいページを取得する複数の方法を提供しています。
page.waitForEvent('popup') でポップアップを待機
例
test('新しいタブの処理', async ({ page }) => {
// クリックする前に新しいページイベントの待機を準備する
const popupPromise = page.waitForEvent('popup');
// 新しいウィンドウを開くリンクをクリック
await page.getByRole('link', { name: '新しいウィンドウで開く' }).click();
// 新しく開かれたページを取得
const popup = await popupPromise;
// 新しいページ上で操作
await expect(popup).toHaveTitle(/サンプル/);
await popup.getByRole('button', { name: '確定' }).click();
// 新しいページを閉じる
await popup.close();
});
// クリックする前に新しいページイベントの待機を準備する
const popupPromise = page.waitForEvent('popup');
// 新しいウィンドウを開くリンクをクリック
await page.getByRole('link', { name: '新しいウィンドウで開く' }).click();
// 新しく開かれたページを取得
const popup = await popupPromise;
// 新しいページ上で操作
await expect(popup).toHaveTitle(/サンプル/);
await popup.getByRole('button', { name: '確定' }).click();
// 新しいページを閉じる
await popup.close();
});
context.on('page') で新しいページを監視
例
test('Context 内のすべての新しいページを監視', async ({ context, page }) => {
// Context 全体の新しいページ作成を監視
context.on('page', async newPage => {
console.log('新しいページが開かれました:', newPage.url());
// 新しいページの読み込み完了を待機
await newPage.waitForLoadState();
// 新しいページ上で操作
});
await page.goto('https://www.example.com/');
// 後続の新しいウィンドウを開く操作は、上記のリスナーを自動的にトリガーします
});
// Context 全体の新しいページ作成を監視
context.on('page', async newPage => {
console.log('新しいページが開かれました:', newPage.url());
// 新しいページの読み込み完了を待機
await newPage.waitForLoadState();
// 新しいページ上で操作
});
await page.goto('https://www.example.com/');
// 後続の新しいウィンドウを開く操作は、上記のリスナーを自動的にトリガーします
});
Playwright のイベントシステム
Playwright の Page オブジェクトと Context オブジェクトはどちらもイベントエミッターであり、さまざまなイベントを監視できます。
よく使うページイベント
| イベント | トリガーのタイミング |
|---|---|
request | ページがネットワークリクエストを開始したとき |
response | ネットワークレスポンスを受信したとき |
dialog | alert/confirm/prompt ダイアログが表示されたとき |
download | ファイルのダウンロードが開始されたとき |
popup | 新しいページ(ポップアップ/新規タブ)が開かれたとき |
console | ページが console メッセージを出力したとき |
pageerror | ページでキャッチされない JavaScript エラーが発生したとき |
load | ページの読み込みが完了したとき |
close | ページが閉じられたとき |
イベントの監視方法
例
// 継続的に監視
page.on('request', request => {
console.log('リクエスト:', request.method(), request.url());
});
// 一度だけの監視(一度トリガーされたら自動的に削除)
page.once('dialog', dialog => {
dialog.accept();
});
// リスナーを削除
const handler = (request) => { /* ... */ };
page.on('request', handler);
page.off('request', handler);
page.on('request', request => {
console.log('リクエスト:', request.method(), request.url());
});
// 一度だけの監視(一度トリガーされたら自動的に削除)
page.once('dialog', dialog => {
dialog.accept();
});
// リスナーを削除
const handler = (request) => { /* ... */ };
page.on('request', handler);
page.off('request', handler);