Skip to main content

頁面

頁面

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