Implementation:Puppeteer Puppeteer Bidi Core BrowsingContext
| Property | Value |
|---|---|
| Implementation | BrowsingContext (core) |
| Source File | packages/puppeteer-core/src/bidi/core/BrowsingContext.ts
|
| Repository | puppeteer/puppeteer |
| Lines | 845 |
| License | Apache-2.0 |
| Copyright | 2024 Google Inc. |
Overview
Description
The BrowsingContext class in the bidi/core module is the low-level representation of a browser browsing context (tab, window, or iframe) in the WebDriver BiDi protocol layer. It directly interfaces with the BiDi session to send commands and processes raw protocol events. This class is the backbone that BidiFrame wraps with higher-level Puppeteer API semantics.
This class extends EventEmitter and emits a rich set of events:
- closed -- When the context is closed.
- browsingcontext -- When a child browsing context is created.
- navigation -- When a navigation starts.
- filedialogopened -- When a file dialog is opened.
- request -- When a network request is made.
- log -- When a log entry is added.
- userprompt -- When a user prompt (dialog) is opened.
- historyUpdated -- When the browsing history is updated.
- DOMContentLoaded -- When the DOMContentLoaded event fires.
- load -- When the load event fires.
- worker -- When a dedicated worker is created.
Key responsibilities:
- Navigation commands:
navigate(url, wait),reload(options),traverseHistory(delta)for back/forward navigation. - Content capture:
captureScreenshot(options)andprint(options)for screenshots and PDF generation. - Context lifecycle:
close(promptUnload),activate()for closing and bringing to front. - Realm management: Creates
WindowRealminstances (default realm on construction, additional sandboxed realms viacreateWindowRealm(sandbox)). ProvidesrealmsanddefaultRealmaccessors. - Child context management: Listens for
browsingContext.contextCreatedevents matching this context as parent and creates childBrowsingContextinstances. Provideschildrenandtopaccessors. - Network request tracking: Listens for
network.beforeRequestSentand createsRequestobjects, tracking them by ID. Emitsrequestevents. - Navigation tracking: Listens for
browsingContext.navigationStarted, createsNavigationobjects, and updates the URL on fragment/failed/aborted events. - Lifecycle events: Listens for
browsingContext.domContentLoaded,browsingContext.load,browsingContext.historyUpdated, andbrowsingContext.contextDestroyedto manage URL updates and disposal. - User prompts: Listens for
browsingContext.userPromptOpenedand createsUserPromptobjects.handleUserPrompt(options)sends the response. - Viewport and emulation:
setViewport(),setTouchOverride(),setScreenOrientationOverride(),setGeolocationOverride(),setTimezoneOverride(),setJavaScriptEnabled(),setUserAgent(),setClientHintsOverride(),setOfflineMode(),setExtraHTTPHeaders(). - Cookie management:
getCookies(),setCookie(),deleteCookie()using BiDi storage commands scoped to this context. - Cache control:
setCacheBehavior()for enabling/disabling cache. - Input:
performActions(),releaseActions(),setFiles()for input simulation. - Preload scripts and intercepts:
addPreloadScript(),removePreloadScript(),addIntercept()scoped to this context. - Node location:
locateNodes()for finding DOM nodes via locator strategies. - Bluetooth and device prompts: Exposes
bluetoothemulation andwaitForDevicePrompt().
The class uses @throwIfDisposed and @inertIfDisposed decorators on all methods and DisposableStack for cleanup of event subscriptions.
Usage
This is an internal class not directly used by Puppeteer consumers. It is created by parent BrowsingContext instances or by UserContext and is wrapped by BidiFrame.
Code Reference
Source Location
packages/puppeteer-core/src/bidi/core/BrowsingContext.ts (GitHub)
Signature
export class BrowsingContext extends EventEmitter<{
closed: {reason: string};
browsingcontext: {browsingContext: BrowsingContext};
navigation: {navigation: Navigation};
filedialogopened: Bidi.Input.FileDialogInfo;
request: {request: Request};
log: {entry: Bidi.Log.Entry};
userprompt: {userPrompt: UserPrompt};
historyUpdated: void;
DOMContentLoaded: void;
load: void;
worker: {realm: DedicatedWorkerRealm};
}> {
static from(
userContext: UserContext,
parent: BrowsingContext | undefined,
id: string,
url: string,
originalOpener: string | null,
clientWindow: string,
): BrowsingContext;
readonly defaultRealm: WindowRealm;
readonly id: string;
readonly parent: BrowsingContext | undefined;
readonly userContext: UserContext;
readonly originalOpener: string | null;
readonly windowId: string;
get children(): Iterable<BrowsingContext>;
get closed(): boolean;
get disposed(): boolean;
get realms(): Iterable<WindowRealm>;
get top(): BrowsingContext;
get url(): string;
get bluetooth(): BluetoothEmulation;
async activate(): Promise<void>;
async captureScreenshot(options?: CaptureScreenshotOptions): Promise<string>;
async close(promptUnload?: boolean): Promise<void>;
async traverseHistory(delta: number): Promise<void>;
async navigate(url: string, wait?: ReadinessState): Promise<void>;
async reload(options?: ReloadOptions): Promise<void>;
async setCacheBehavior(cacheBehavior: 'default' | 'bypass'): Promise<void>;
async print(options?: PrintOptions): Promise<string>;
async handleUserPrompt(options?: HandleUserPromptOptions): Promise<void>;
async setViewport(options?: SetViewportOptions): Promise<void>;
async setTouchOverride(maxTouchPoints: number | null): Promise<void>;
async performActions(actions: Bidi.Input.SourceActions[]): Promise<void>;
async releaseActions(): Promise<void>;
createWindowRealm(sandbox: string): WindowRealm;
async addPreloadScript(functionDeclaration: string, options?: AddPreloadScriptOptions): Promise<string>;
async addIntercept(options: AddInterceptOptions): Promise<string>;
async removePreloadScript(script: string): Promise<void>;
async setGeolocationOverride(options: SetGeoLocationOverrideOptions): Promise<void>;
async setTimezoneOverride(timezoneId?: string): Promise<void>;
async setScreenOrientationOverride(screenOrientation: ScreenOrientation | null): Promise<void>;
async getCookies(options?: GetCookiesOptions): Promise<Bidi.Network.Cookie[]>;
async setCookie(cookie: Bidi.Storage.PartialCookie): Promise<void>;
async setFiles(element: Bidi.Script.SharedReference, files: string[]): Promise<void>;
async deleteCookie(...cookieFilters: Bidi.Storage.CookieFilter[]): Promise<void>;
async locateNodes(
locator: Bidi.BrowsingContext.Locator,
startNodes?: Bidi.Script.SharedReference[],
): Promise<Bidi.Script.NodeRemoteValue[]>;
async setJavaScriptEnabled(enabled: boolean): Promise<void>;
isJavaScriptEnabled(): boolean;
async setUserAgent(userAgent: string | null): Promise<void>;
async setClientHintsOverride(clientHints: ClientHintsMetadata | null): Promise<void>;
async setOfflineMode(enabled: boolean): Promise<void>;
async waitForDevicePrompt(timeout: number, signal?: AbortSignal): Promise<DeviceRequestPrompt>;
async setExtraHTTPHeaders(headers: Record<string, string>): Promise<void>;
}
Import
import {BrowsingContext} from './core/BrowsingContext.js';
I/O Contract
Inputs (Factory)
| Parameter | Type | Description |
|---|---|---|
| userContext | UserContext |
The user context this browsing context belongs to |
| parent | undefined | Parent context for iframes, undefined for top-level |
| id | string |
The browsing context ID |
| url | string |
The initial URL |
| originalOpener | null | The ID of the opener context (for popups) |
| clientWindow | string |
The client window ID |
Key Method Parameters
| Method | Parameter | Type | Description |
|---|---|---|---|
| navigate | url | string |
URL to navigate to |
| navigate | wait | ReadinessState |
When to consider navigation complete (interactive, complete) |
| captureScreenshot | options | CaptureScreenshotOptions |
Format, origin, clip region |
| options | PrintOptions |
PDF options (margin, orientation, page size, scale) | |
| setViewport | options | SetViewportOptions |
Viewport width, height, devicePixelRatio |
| performActions | actions | SourceActions[] |
BiDi input source actions (keyboard, mouse, touch) |
| setGeolocationOverride | options | SetGeoLocationOverrideOptions |
Coordinates to emulate |
| locateNodes | locator | Bidi.BrowsingContext.Locator |
Locator strategy for finding nodes |
Outputs
| Method | Return Type | Description |
|---|---|---|
| captureScreenshot | Promise<string> |
Base64-encoded screenshot data |
Promise<string> |
Base64-encoded PDF data | |
| getCookies | Promise<Bidi.Network.Cookie[]> |
Array of BiDi cookie objects |
| addPreloadScript | Promise<string> |
The preload script ID |
| addIntercept | Promise<string> |
The network intercept ID |
| locateNodes | Promise<NodeRemoteValue[]> |
Found DOM nodes |
| url | string |
Current URL of the context |
| children | Iterable<BrowsingContext> |
Child browsing contexts |
| top | BrowsingContext |
Top-level ancestor context |
Usage Examples
// Internal usage -- navigating a browsing context
await browsingContext.navigate('https://example.com', 'interactive');
// Capture a screenshot
const screenshot = await browsingContext.captureScreenshot({
origin: 'viewport',
format: {type: 'image/png'},
});
// Print to PDF
const pdf = await browsingContext.print({
orientation: 'portrait',
page: {width: 21, height: 29.7}, // A4 in cm
background: true,
});
// Set viewport
await browsingContext.setViewport({
viewport: {width: 1280, height: 720},
devicePixelRatio: 2,
});
// Perform input actions
await browsingContext.performActions([
{
type: 'pointer',
id: '__puppeteer_mouse',
actions: [
{type: 'pointerMove', x: 100, y: 200},
{type: 'pointerDown', button: 0},
{type: 'pointerUp', button: 0},
],
},
]);
// Manage cookies
const cookies = await browsingContext.getCookies();
await browsingContext.setCookie({
domain: '.example.com',
name: 'session',
value: {type: 'string', value: 'abc123'},
});
// Locate nodes
const nodes = await browsingContext.locateNodes({
type: 'css',
value: 'button.submit',
});