Skip to main content
Version: 1.15

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.

const { chromium } = require('playwright');
// Create a Chromium browser instanceconst browser = await chromium.launch();
// Create two isolated browser contextsconst userContext = await browser.newContext();const adminContext = await browser.newContext();
// Create pages and interact with contexts independently

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 pagesconst pageOne = await context.newPage();const pageTwo = await context.newPage();
// Get pages of a browser contextconst allPages = 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)const [newPage] = await Promise.all([  context.waitForEvent('page'),  page.click('a[target="_blank"]') // Opens a new tab])await newPage.waitForLoadState();console.log(await newPage.title());

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

// Get all new pages (including popups) in the contextcontext.on('page', async page => {  await page.waitForLoadState();  console.log(await page.title());})

API reference#

Handling popups#

If the page opens a pop-up (e.g. pages opened by target="_blank" links), 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)const [popup] = await Promise.all([  page.waitForEvent('popup'),  page.click('#open')]);await popup.waitForLoadState();console.log(await popup.title());

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

// Get all popups when they openpage.on('popup', async popup => {  await popup.waitForLoadState();  await popup.title();})

API reference#