Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Puppeteer Puppeteer Bidi Core Realm

From Leeroopedia
Property Value
Implementation Realm, WindowRealm, DedicatedWorkerRealm, SharedWorkerRealm (core)
Source File packages/puppeteer-core/src/bidi/core/Realm.ts
Repository puppeteer/puppeteer
Lines 338
License Apache-2.0
Copyright 2024 Google Inc.

Overview

Description

This module defines the low-level WebDriver BiDi script execution realm classes that sit beneath the high-level BidiRealm / BidiFrameRealm / BidiWorkerRealm wrappers. These classes directly interface with the BiDi session to execute JavaScript via script.callFunction, script.evaluate, and script.disown commands.

Realm (abstract) is the base class for all realm types. It:

  • Has an id and origin that are set on construction and may be updated during the realm lifecycle.
  • Emits updated when the realm identity changes (e.g., after navigation), destroyed when the realm is disposed, and worker/sharedworker when child workers are created.
  • Provides callFunction(functionDeclaration, awaitPromise, options) for calling JavaScript functions with arguments, serialization options, and result ownership control.
  • Provides evaluate(expression, awaitPromise, options) for evaluating JavaScript expressions.
  • Provides disown(handles) for releasing remote object handles.
  • Provides resolveExecutionContextId() for obtaining the CDP execution context ID via the goog:cdp.resolveRealm extension command.
  • Uses @throwIfDisposed to prevent operations on destroyed realms and DisposableStack for cleanup.

WindowRealm represents a window (frame) execution context. It:

  • Is associated with a BrowsingContext and an optional sandbox name.
  • Creates a default realm on construction and additional sandboxed realms via the factory.
  • Listens for script.realmCreated events of type window matching its context and sandbox to update its id and origin.
  • Listens for script.realmCreated events of type dedicated-worker owned by this realm and creates DedicatedWorkerRealm instances.
  • Uses a target of {context: browsingContext.id, sandbox} instead of {realm: id}.

DedicatedWorkerRealm represents a dedicated web worker execution context. It:

  • Has an owners set tracking the parent realm(s).
  • Listens for script.realmDestroyed for self-destruction.
  • Listens for script.realmCreated of type dedicated-worker for nested workers.
  • Delegates session access through its owner chain.

SharedWorkerRealm represents a shared web worker execution context. It:

  • Has a reference to the Browser core object.
  • Listens for script.realmDestroyed and nested dedicated-worker creation events.
  • Accesses the session through the browser.

The module also exports type aliases CallFunctionOptions and EvaluateOptions which omit the target and function/expression parameters from the raw BiDi types.

Usage

These are internal classes used by BidiRealm, BidiFrameRealm, BidiWorkerRealm, and BrowsingContext. They are not exposed to Puppeteer consumers.

Code Reference

Source Location

packages/puppeteer-core/src/bidi/core/Realm.ts (GitHub)

Signature

export type CallFunctionOptions = Omit<
  Bidi.Script.CallFunctionParameters,
  'functionDeclaration' | 'awaitPromise' | 'target'
>;

export type EvaluateOptions = Omit<
  Bidi.Script.EvaluateParameters,
  'expression' | 'awaitPromise' | 'target'
>;

export abstract class Realm extends EventEmitter<{
  updated: Realm;
  destroyed: {reason: string};
  worker: DedicatedWorkerRealm;
  sharedworker: SharedWorkerRealm;
}> {
  readonly id: string;
  readonly origin: string;

  get disposed(): boolean;
  protected abstract get session(): Session;
  get target(): Bidi.Script.Target;

  protected dispose(reason?: string): void;
  async disown(handles: string[]): Promise<void>;
  async callFunction(
    functionDeclaration: string,
    awaitPromise: boolean,
    options?: CallFunctionOptions,
  ): Promise<Bidi.Script.EvaluateResult>;
  async evaluate(
    expression: string,
    awaitPromise: boolean,
    options?: EvaluateOptions,
  ): Promise<Bidi.Script.EvaluateResult>;
  async resolveExecutionContextId(): Promise<number>;
}

export class WindowRealm extends Realm {
  static from(context: BrowsingContext, sandbox?: string): WindowRealm;
  readonly browsingContext: BrowsingContext;
  readonly sandbox?: string;
  override get session(): Session;
  override get target(): Bidi.Script.Target;
}

export class DedicatedWorkerRealm extends Realm {
  static from(owner: DedicatedWorkerOwnerRealm, id: string, origin: string): DedicatedWorkerRealm;
  readonly owners: Set<DedicatedWorkerOwnerRealm>;
  override get session(): Session;
}

export class SharedWorkerRealm extends Realm {
  static from(browser: Browser, id: string, origin: string): SharedWorkerRealm;
  readonly browser: Browser;
  override get session(): Session;
}

export type DedicatedWorkerOwnerRealm = DedicatedWorkerRealm | SharedWorkerRealm | WindowRealm;

Import

import {Realm, WindowRealm, DedicatedWorkerRealm, SharedWorkerRealm} from './core/Realm.js';

I/O Contract

Inputs

Parameter Type Description
context (WindowRealm) BrowsingContext The browsing context this window realm belongs to
sandbox (WindowRealm) string Optional sandbox name for isolated realms
owner (DedicatedWorkerRealm) DedicatedWorkerOwnerRealm The parent realm that owns this worker
browser (SharedWorkerRealm) Browser The core browser instance
id string The realm ID
origin string The realm origin

Key Method Parameters

Method Parameter Type Description
callFunction functionDeclaration string Stringified JavaScript function
callFunction awaitPromise boolean Whether to await the result if it is a Promise
callFunction options.arguments LocalValue[] Arguments to pass to the function
callFunction options.resultOwnership ResultOwnership Whether the result should be owned (root) or not (none)
evaluate expression string JavaScript expression to evaluate
disown handles string[] Remote object handle IDs to release

Outputs

Method Return Type Description
callFunction Promise<EvaluateResult> The BiDi evaluate result containing the return value or exception
evaluate Promise<EvaluateResult> The BiDi evaluate result
resolveExecutionContextId Promise<number> The CDP execution context ID for this realm
target Bidi.Script.Target The target specifier for script commands
disposed boolean Whether this realm has been destroyed

Usage Examples

// Internal usage -- calling a function in a window realm
const result = await windowRealm.callFunction(
  'function(a, b) { return a + b; }',
  true, // awaitPromise
  {
    arguments: [
      {type: 'number', value: 1},
      {type: 'number', value: 2},
    ],
    resultOwnership: 'none',
  },
);

// Evaluate an expression
const evalResult = await windowRealm.evaluate(
  'document.title',
  true,
  {resultOwnership: 'none'},
);

// Disown handles to free memory
await windowRealm.disown(['handle-id-1', 'handle-id-2']);

// Resolve the CDP execution context ID
const contextId = await windowRealm.resolveExecutionContextId();

// Check the target specifier
console.log(windowRealm.target);
// {context: 'context-id', sandbox: undefined}

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment