ページ
ページ
各BrowserContextは複数のページを持つことができます。Pageは、ブラウザコンテキスト内の単一のタブまたはポップアップウィンドウを指します。URL に移動し、ページコンテンツを操作するために使用する必要があります。
// Create a page.
var page = await context.NewPageAsync();
// Navigate explicitly, similar to entering a URL in the browser.
await page.GotoAsync("http://example.com");
// Fill an input.
await page.Locator("#search").FillAsync("query");
// Navigate implicitly by clicking a link.
await page.Locator("#submit").ClickAsync();
// Expect a new url.
Console.WriteLine(page.Url);
複数のページ
各ブラウザコンテキストは、複数のページ(タブ)をホストできます。
- 各ページは、フォーカスされたアクティブなページのように動作します。ページを前面に表示する必要はありません。
- コンテキスト内のページは、ビューポートサイズ、カスタムネットワークルート、ブラウザロケールなどのコンテキストレベルのエミュレーションに従います。
// Create two pages
var pageOne = await context.NewPageAsync();
var pageTwo = await context.NewPageAsync();
// Get pages of a browser context
var allPages = context.Pages;
新しいページの処理
ブラウザコンテキストの page
イベントを使用すると、コンテキストで作成された新しいページを取得できます。これは、target="_blank"
リンクによって開かれた新しいページを処理するために使用できます。
// Get page after a specific action (e.g. clicking a link)
var newPage = await context.RunAndWaitForPageAsync(async () =>
{
await page.GetByText("open new tab").ClickAsync();
});
// Interact with the new page normally
await newPage.GetByRole(AriaRole.Button).ClickAsync();
Console.WriteLine(await newPage.TitleAsync());
新しいページをトリガーするアクションが不明な場合は、次のパターンを使用できます。
// Get all new pages (including popups) in the context
context.Page += async (_, page) => {
await page.WaitForLoadStateAsync();
Console.WriteLine(await page.TitleAsync());
};
ポップアップの処理
ページがポップアップを開く場合(例:target="_blank"
リンクによって開かれたページ)、ページの popup
イベントをリッスンすることで、ポップアップへの参照を取得できます。
このイベントは、browserContext.on('page')
イベントに加えて発行されますが、このページに関連するポップアップのみが対象です。
// Get popup after a specific action (e.g., click)
var popup = await page.RunAndWaitForPopupAsync(async () =>
{
await page.GetByText("open the popup").ClickAsync();
});
// Interact with the popup normally
await popup.GetByRole(AriaRole.Button).ClickAsync();
Console.WriteLine(await popup.TitleAsync());
ポップアップをトリガーするアクションが不明な場合は、次のパターンを使用できます。
// Get all popups when they open
page.Popup += async (_, popup) => {
await popup.WaitForLoadStateAsync();
Console.WriteLine(await page.TitleAsync());
};