Implementation:Microsoft Playwright LaunchContext
| Knowledge Sources | |
|---|---|
| Domains | Testing, Code_Generation, Browser_Configuration |
| Last Updated | 2026-02-11 00:00 GMT |
Overview
Concrete tool for configuring and launching a browser context with device emulation, viewport, geolocation, and other settings for recording sessions, provided by the Playwright library.
Description
The launchContext function is an internal utility used by the Playwright CLI to translate command-line options into a fully configured browser context. It serves as the bridge between the user-facing CLI arguments and the Playwright browser API.
The function performs the following steps:
- Device resolution: If a
--deviceoption is provided, the function looks up the device descriptor fromplaywright.devices[name](L393) and uses it as the base configuration. - Option merging: Explicit CLI options (viewport, geolocation, color scheme, etc.) override the device defaults.
- Browser launch: The appropriate browser type (Chromium, Firefox, or WebKit) is launched with the computed
launchOptions. - Context creation: A new browser context is created with the computed
contextOptions, which include viewport, user agent, device scale factor, geolocation permissions, color scheme, timezone, locale, and proxy settings. - Storage loading: If
--load-storageis specified, saved cookies and localStorage entries are loaded into the context. - Cleanup registration: A
closeBrowsercallback is prepared that optionally saves storage state before closing the browser.
The function returns a structured object containing all the computed settings alongside the live browser and context instances, enabling the caller (the codegen command) to further configure the context for recording.
Usage
Use this function when you need to:
- Launch a browser context with CLI-derived configuration for any Playwright CLI command (codegen, open, screenshot, pdf).
- Resolve device profiles to concrete browser context options.
- Merge multiple layers of configuration (defaults, device profile, explicit overrides).
This function is internal to the CLI and not part of the public Playwright API.
Code Reference
Source Location
- Repository: playwright
- File:
packages/playwright-core/src/cli/program.ts - Lines: L383-537
Signature
async function launchContext(
options: Options,
extraOptions: LaunchOptions
): Promise<{
browser: Browser;
browserName: string;
context: BrowserContext;
contextOptions: BrowserContextOptions;
launchOptions: LaunchOptions;
closeBrowser: () => Promise<void>;
}>
Import
// Internal function - not a public API import
// Defined in packages/playwright-core/src/cli/program.ts
// Used by the codegen, open, screenshot, and pdf CLI commands
Options Type
// Options type defined at L354-374
type Options = {
browser?: string; // 'cr' | 'ff' | 'wk'
device?: string; // Device name from playwright.devices
viewportSize?: string; // 'width,height' format
geolocation?: string; // 'latitude,longitude' format
colorScheme?: string; // 'light' | 'dark' | 'no-preference'
timezone?: string; // IANA timezone ID
proxyServer?: string; // Proxy URL
proxyBypass?: string; // Proxy bypass list
loadStorage?: string; // Path to storage state JSON
saveStorage?: string; // Path to save storage state
lang?: string; // Accept-Language value
userAgent?: string; // Custom user agent string
// ... additional open options
};
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| options | Options | Yes | CLI options parsed by commander.js, containing browser choice, device name, viewport, geolocation, and other context configuration parameters. |
| extraOptions | LaunchOptions | Yes | Additional launch options (e.g., headless mode, executable path) to merge with computed launch options. |
Outputs
| Name | Type | Description |
|---|---|---|
| browser | Browser | The launched browser instance (Chromium, Firefox, or WebKit). |
| browserName | string | The name of the launched browser ('chromium', 'firefox', or 'webkit').
|
| context | BrowserContext | The configured browser context with all options applied (viewport, emulation, storage state, etc.). |
| contextOptions | BrowserContextOptions | The computed context options object, useful for embedding in generated test code. |
| launchOptions | LaunchOptions | The computed launch options object, useful for embedding in generated test code. |
| closeBrowser | () => Promise<void> | Async callback that saves storage state (if --save-storage was specified) and then closes the browser.
|
Usage Examples
Basic Example
// Internal usage within the codegen command handler
const { browser, browserName, context, contextOptions, launchOptions, closeBrowser } =
await launchContext(options, { headless: false });
// Enable recording on the context
await context._enableRecorder({
mode: 'recording',
language: options.target || 'playwright-test',
testIdAttributeName: options.testIdAttribute,
outputFile: options.output,
launchOptions,
contextOptions,
});
Device Emulation Example
// When --device "iPhone 13" is passed:
// 1. Device descriptor is resolved:
const device = playwright.devices['iPhone 13'];
// device = {
// userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X)...',
// viewport: { width: 390, height: 844 },
// deviceScaleFactor: 3,
// isMobile: true,
// hasTouch: true,
// }
// 2. Device options are merged into contextOptions
// 3. Any explicit CLI overrides take precedence over device defaults
Storage State Example
// When --load-storage auth.json is passed:
// The storage state file is loaded after context creation:
// auth.json contains:
// {
// "cookies": [...],
// "origins": [{ "origin": "https://example.com", "localStorage": [...] }]
// }
// When --save-storage state.json is passed:
// closeBrowser() will call:
await context.storageState({ path: 'state.json' });
// before closing the browser
Related Pages
Implements Principle
Requires Environment
- Environment:Microsoft_Playwright_Browser_Binaries_Environment
- Environment:Microsoft_Playwright_Platform_Support_Environment