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

ページ

ページ

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