Version: Next

Multi-page scenarios

Playwright can automate scenarios that span multiple browser contexts or multiple tabs in a browser window.

Multiple contexts#

Browser contexts are isolated environments on a single browser instance. Playwright can create multiple browser contexts within a single scenario. This is useful when you want to test for multi-user functionality, like chat.

from playwright.sync_api import sync_playwright
def run(playwright):
# create a chromium browser instance
chromium = playwright.chromium
browser = chromium.launch()
# create two isolated browser contexts
user_context = browser.new_context()
admin_context = browser.new_context()
# load user and admin cookies
with sync_playwright() as playwright:

API reference#

Multiple pages#

Each browser context can host multiple pages (tabs).

  • Each page behaves like a focused, active page. Bringing the page to front is not required.
  • Pages inside a context respect context-level emulation, like viewport sizes, custom network routes or browser locale.
# create two pages
page_one = context.new_page()
page_two = context.new_page()
# get pages of a brower context
all_pages = context.pages()

API reference#

Handling new pages#

The page event on browser contexts can be used to get new pages that are created in the context. This can be used to handle new pages opened by target="_blank" links.

# Get page after a specific action (e.g. clicking a link)
with context.expect_page() as new_page_info:'a[target="_blank"]') # Opens a new tab
new_page = new_page_info.value

If the action that triggers the new page is unknown, the following pattern can be used.

# Get all new pages (including popups) in the context
def handle_page(page):
context.on("page", handle_page)

API reference#

Handling popups#

If the page opens a pop-up, you can get a reference to it by listening to the popup event on the page.

This event is emitted in addition to the browserContext.on('page') event, but only for popups relevant to this page.

# Get popup after a specific action (e.g., click)
with page.expect_popup() as popup_info:"#open")
popup = popup_info.value

If the action that triggers the popup is unknown, the following pattern can be used.

# Get all popups when they open
def handle_popup(popup):
page.on("popup", handle_popup)

API reference#