页面
页面
每个BrowserContext可以包含多个页面。Page指的是浏览器上下文中的单个标签页或弹出窗口。它用于导航到URL并与页面内容进行交互。
// Create a page.
Page page = context.newPage();
// Navigate explicitly, similar to entering a URL in the browser.
page.navigate("http://example.com");
// Fill an input.
page.locator("#search").fill("query");
// Navigate implicitly by clicking a link.
page.locator("#submit").click();
// Expect a new url.
System.out.println(page.url());
多页面
每个浏览器上下文可以托管多个页面(标签页)。
- 每个页面的行为都像一个获得焦点且活跃的页面,无需将页面置于最前。
- 上下文中的页面会遵循上下文级别的模拟设置,例如视口尺寸、自定义网络路由或浏览器区域设置。
// Create two pages
Page pageOne = context.newPage();
Page pageTwo = context.newPage();
// Get pages of a browser context
List<Page> allPages = context.pages();
处理新页面
浏览器上下文中的page
事件可用于获取在该上下文中创建的新页面。这可用于处理由target="_blank"
链接打开的新页面。
// Get page after a specific action (e.g. clicking a link)
Page newPage = context.waitForPage(() -> {
page.getByText("open new tab").click(); // Opens a new tab
});
// Interact with the new page normally
newPage.getByRole(AriaRole.BUTTON).click();
System.out.println(newPage.title());
如果触发新页面的操作未知,可以使用以下模式。
// Get all new pages (including popups) in the context
context.onPage(page -> {
page.waitForLoadState();
System.out.println(page.title());
});
处理弹窗
如果页面弹出一个新窗口(例如通过target="_blank"
链接打开的页面),您可以通过监听页面上的popup
事件来获取对该窗口的引用。
除了browserContext.on('page')
事件外,还会发出此事件,但仅针对与此页面相关的弹出窗口。
// Get popup after a specific action (e.g., click)
Page popup = page.waitForPopup(() -> {
page.getByText("open the popup").click();
});
// Interact with the popup normally
popup.getByRole(AriaRole.BUTTON).click();
System.out.println(popup.title());
如果触发弹出窗口的操作未知,可以使用以下模式。
// Get all popups when they open
page.onPopup(popup -> {
popup.waitForLoadState();
System.out.println(popup.title());
});