Implementation:Puppeteer Puppeteer Bidi Core Browser
| Property | Value |
|---|---|
| Implementation | Browser (core) |
| Source File | packages/puppeteer-core/src/bidi/core/Browser.ts
|
| Repository | puppeteer/puppeteer |
| Lines | 330 |
| License | Apache-2.0 |
| Copyright | 2024 Google Inc. |
Overview
Description
The Browser class in the bidi/core module is the low-level representation of a browser instance in the WebDriver BiDi protocol layer. It sits below the high-level BidiBrowser class and directly interfaces with the BiDi session to manage user contexts, browsing contexts, preload scripts, network intercepts, extensions, and window state.
This class extends EventEmitter and emits three events:
- closed -- Emitted before the browser closes, with a reason string.
- disconnected -- Emitted after the browser disconnects, with a reason string.
- sharedworker -- Emitted when a shared worker is created, with the realm object.
Key responsibilities:
- Session management: Wraps a
Sessionobject. Listens for session end events to trigger disposal. - User context synchronization: On initialization, calls
browser.getUserContextsto discover existing user contexts andbrowsingContext.getTreeto discover existing browsing contexts. SimulatesbrowsingContext.contextCreatedevents for contexts discovered during the tree walk. - User context lifecycle:
createUserContext()creates new user contexts with optional proxy configuration and download behavior policies. Manages user context creation/cleanup via event emitters and a disposable stack. - Shared worker tracking: Listens for
script.realmCreatedevents of typeshared-workerand createsSharedWorkerRealminstances. - Preload scripts:
addPreloadScript()andremovePreloadScript()sendscript.addPreloadScriptandscript.removePreloadScriptcommands. - Network intercepts:
removeIntercept()sendsnetwork.removeIntercept. - Extensions:
installExtension()anduninstallExtension()viawebExtension.install/webExtension.uninstall. - Window management:
setClientWindowState()andgetClientWindowInfo()for controlling browser window bounds. - Disposal: Uses
DisposableStackfor cleanup. Thedispose()method sets the closed/disconnected state and emits appropriate events.
The class uses @throwIfDisposed and @inertIfDisposed decorators to guard against operations on disconnected browsers.
Usage
This is an internal class not directly used by Puppeteer consumers. It is created by Session.from() during browser initialization and is wrapped by BidiBrowser.
Code Reference
Source Location
packages/puppeteer-core/src/bidi/core/Browser.ts (GitHub)
Signature
export class Browser extends EventEmitter<{
closed: {reason: string};
disconnected: {reason: string};
sharedworker: {realm: SharedWorkerRealm};
}> {
static async from(session: Session): Promise<Browser>;
readonly session: Session;
get closed(): boolean;
get defaultUserContext(): UserContext;
get disconnected(): boolean;
get disposed(): boolean;
get userContexts(): Iterable<UserContext>;
dispose(reason?: string, closed?: boolean): void;
async close(): Promise<void>;
async addPreloadScript(
functionDeclaration: string, options?: AddPreloadScriptOptions
): Promise<string>;
async removeIntercept(intercept: Bidi.Network.Intercept): Promise<void>;
async removePreloadScript(script: string): Promise<void>;
async createUserContext(options: BrowserContextOptions): Promise<UserContext>;
async installExtension(path: string): Promise<string>;
async uninstallExtension(id: string): Promise<void>;
async setClientWindowState(
params: Bidi.Browser.SetClientWindowStateParameters
): Promise<void>;
async getClientWindowInfo(windowId: string): Promise<Bidi.Browser.ClientWindowInfo>;
}
Import
import {Browser} from './core/Browser.js';
I/O Contract
Inputs
| Parameter | Type | Description |
|---|---|---|
| session | Session |
The BiDi session established with the browser |
Key Method Parameters
| Method | Parameter | Type | Description |
|---|---|---|---|
| addPreloadScript | functionDeclaration | string |
JavaScript function to execute on new documents |
| addPreloadScript | options.contexts | BrowsingContext[] |
Optional contexts to scope the script to |
| createUserContext | options.proxyServer | string |
Optional proxy server URL |
| createUserContext | options.proxyBypassList | string[] |
Optional proxy bypass list |
| createUserContext | options.downloadBehavior | object |
Download behavior policy (allow, deny, allowAndName) |
| installExtension | path | string |
File system path to the extension |
| setClientWindowState | params | SetClientWindowStateParameters |
Window ID, state, position, and size |
| getClientWindowInfo | windowId | string |
The client window ID |
Outputs
| Method | Return Type | Description |
|---|---|---|
| from | Promise<Browser> |
An initialized core browser instance |
| close | Promise<void> |
Sends browser.close and disposes |
| addPreloadScript | Promise<string> |
The preload script ID |
| createUserContext | Promise<UserContext> |
The newly created user context |
| installExtension | Promise<string> |
The extension ID |
| getClientWindowInfo | Promise<ClientWindowInfo> |
Window position, size, and state |
| userContexts | Iterable<UserContext> |
All user contexts |
| defaultUserContext | UserContext |
The default user context |
Usage Examples
// Internal usage -- creating a core browser from a session
const browser = await Browser.from(session);
// Create a user context with proxy
const userContext = await browser.createUserContext({
proxyServer: 'http://proxy:8080',
proxyBypassList: ['localhost'],
});
// Add a preload script globally
const scriptId = await browser.addPreloadScript(
'() => { window.__injected = true; }'
);
// Remove the preload script
await browser.removePreloadScript(scriptId);
// Install an extension
const extId = await browser.installExtension('/path/to/ext');
await browser.uninstallExtension(extId);
// Manage window state
await browser.setClientWindowState({
clientWindow: 'window-1',
state: 'normal',
width: 1024,
height: 768,
});
// Get window info
const info = await browser.getClientWindowInfo('window-1');
console.log(info.width, info.height, info.state);
// Close the browser
await browser.close();