跳转到主要内容

页面

页面

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