メインコンテンツへスキップ

ページ

ページ

BrowserContext は複数のページを持つことができます。Page は、ブラウザコンテキスト内の単一のタブまたはポップアップウィンドウを指します。URL に移動し、ページコンテンツを操作するために使用する必要があります。

// Create a page.
const page = await context.newPage();

// Navigate explicitly, similar to entering a URL in the browser.
await page.goto('http://example.com');
// Fill an input.
await page.locator('#search').fill('query');

// Navigate implicitly by clicking a link.
await page.locator('#submit').click();
// Expect a new url.
console.log(page.url());

複数のページ

各ブラウザコンテキストは、複数のページ(タブ)をホストできます。

  • 各ページは、フォーカスされたアクティブなページのように動作します。ページを前面に表示する必要はありません。
  • コンテキスト内のページは、ビューポートサイズ、カスタムネットワークルート、またはブラウザロケールなど、コンテキストレベルのエミュレーションを尊重します。
// Create two pages
const pageOne = await context.newPage();
const pageTwo = await context.newPage();

// Get pages of a browser context
const allPages = context.pages();

新しいページの処理

ブラウザコンテキストの page イベントを使用して、コンテキストで作成された新しいページを取得できます。これは、target="_blank" リンクによって開かれた新しいページを処理するために使用できます。

// Start waiting for new page before clicking. Note no await.
const pagePromise = context.waitForEvent('page');
await page.getByText('open new tab').click();
const newPage = await pagePromise;
// Interact with the new page normally.
await newPage.getByRole('button').click();
console.log(await newPage.title());

新しいページをトリガーするアクションが不明な場合は、次のパターンを使用できます。

// Get all new pages (including popups) in the context
context.on('page', async page => {
await page.waitForLoadState();
console.log(await page.title());
});

ポップアップの処理

ページがポップアップ(例えば、target="_blank" リンクによって開かれたページ)を開く場合、ページの popup イベントをリッスンすることで、その参照を取得できます。

このイベントは、browserContext.on('page') イベントに加えて発行されますが、このページに関連するポップアップのみが対象です。

// Start waiting for popup before clicking. Note no await.
const popupPromise = page.waitForEvent('popup');
await page.getByText('open the popup').click();
const popup = await popupPromise;
// Interact with the new popup normally.
await popup.getByRole('button').click();
console.log(await popup.title());

ポップアップをトリガーするアクションが不明な場合は、次のパターンを使用できます。

// Get all popups when they open
page.on('popup', async popup => {
await popup.waitForLoadState();
console.log(await popup.title());
});