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.

  1. const { chromium } = require('playwright');
  2. // Create a Chromium browser instance
  3. const browser = await chromium.launch();
  4. // Create two isolated browser contexts
  5. const userContext = await browser.newContext();
  6. const adminContext = await browser.newContext();
  7. // Load user and admin cookies
  8. await userContext.addCookies(userCookies);
  9. await adminContext.addCookies(adminCookies);

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.
  1. // Create two pages
  2. const pageOne = await context.newPage();
  3. const pageTwo = await context.newPage();
  4. // Get pages of a brower context
  5. const 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.

  1. // Get page after a specific action (e.g. clicking a link)
  2. const [newPage] = await Promise.all([
  3. context.waitForEvent('page'),
  4. page.evaluate(() => window.open('https://google.com', '_blank'))
  5. ])
  6. await newPage.waitForLoadState();
  7. console.log(await newPage.title());
  8. // Get all new pages (including popups) in the context
  9. context.on('page', async page => {
  10. await page.waitForLoadState();
  11. await page.title();
  12. })

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.

  1. // Get popup after a specific action (e.g., click)
  2. const [popup] = await Promise.all([
  3. page.waitForEvent('popup'),
  4. page.click('#open')
  5. ]);
  6. await popup.waitForLoadState();
  7. await popup.title();
  8. // Get all popups when they open
  9. page.on('popup', async popup => {
  10. await popup.waitForLoadState();
  11. await popup.title();
  12. })

API reference