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