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:

Browser browser = chromium.launch();
BrowserContext context = browser.newContext();
Page page = context.newPage();

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

// FIXME
import com.microsoft.playwright.*;

public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType devices = playwright.devices();
BrowserContext context = browser.newContext(new Browser.NewContextOptions()
.setUserAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0 Mobile/15E148 Safari/604.1")
.setViewportSize(375, 812)
.setDeviceScaleFactor(3)
.setIsMobile(true)
.setHasTouch(true)
.setPermissions(Arrays.asList("geolocation"))
.setGeolocation(52.52, 13.39)
.setColorScheme(ColorScheme.DARK)
.setLocale("de-DE"));
Page page = context.newPage();
}
}
}

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.

import com.microsoft.playwright.*;

public class Example {
public static void main(String[] args) {
try (Playwright playwright = Playwright.create()) {
BrowserType chromium = playwright.chromium();
// Create a Chromium browser instance
Browser browser = chromium.launch();
// Create two isolated browser contexts
BrowserContext userContext = browser.newContext();
BrowserContext adminContext = browser.newContext();
// Create pages and interact with contexts independently
}
}
}

API reference