Skip to main content
Version: 1.17

Browser Contexts

Browser context

A BrowserContext is an isolated incognito-alike session within a browser instance. Browser contexts are fast and cheap to create. We recommend running each test scenario in its own new Browser context, so that the browser state is isolated between the tests. If you are using Playwright Test, this happens out of the box for each test. Otherwise, you can create browser contexts manually:

await using var browser = playwright.Chromium.LaunchAsync();
var context = await browser.NewContextAsync();
var page = await context.NewPageAsync();

Browser contexts can also be used to emulate multi-page scenarios involving mobile devices, permissions, locale and color scheme.

using Microsoft.Playwright;
using System.Threading.Tasks;

class PlaywrightExample
{
public static async Task Main()
{
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Webkit.LaunchAsync();
var options = new BrowserNewContextOptions(playwright.Devices["iPhone 11 Pro"])
{
Geolocation = new() { Longitude = 12.492507f, Latitude = 41.889938f },
Permissions = new[] { "geolocation" },
Locale = "de-DE"
};

await using var context = await browser.NewContextAsync(options);
var page = await browser.NewPageAsync();
}
}

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