跳至主要内容

页面

页面

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