Skip to main content
Version: 1.12.0

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.

using Microsoft.Playwright;
using System.Threading.Tasks;
class Program
{
public static async Task Main()
{
using var playwright = await Playwright.CreateAsync();
// Create a Chromium browser instance
await using var browser = await playwright.Chromium.LaunchAsync();
await using var userContext = await browser.NewContextAsync();
await using var adminContext = await browser.NewContextAsync();
// 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 pages
var pageOne = await context.NewPageAsync();
var pageTwo = await context.NewPageAsync();
// Get pages of a brower context
var 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)
var newPage = await context.RunAndWaitForPageAsync(async () =>
{
await page.ClickAsync("a[target='_blank']");
});
await newPage.WaitForLoadStateAsync();
Console.WriteLine(await newPage.TitleAsync());

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
context.Page += async (_, page) => {
await page.WaitForLoadStateAsync();
Console.WriteLine(await page.TitleAsync());
};

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)
var newPage = await page.RunAndWaitForPopupAsync(async () =>
{
await page.ClickAsync("#open");
});
await newPage.WaitForLoadStateAsync();
Console.WriteLine(await newPage.TitleAsync());

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

// Get all popups when they open
page.Popup += async (_, popup) => {
await popup.WaitForLoadStateAsync();
Console.WriteLine(await page.TitleAsync());
};

API reference#