跳到主要內容

頁面

頁面

每個 BrowserContext 可以有多個頁面。頁面指的是瀏覽器上下文中的單一分頁或彈出視窗。它應該用於導航到 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());
});