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 Request

From Leeroopedia
Property Value
Implementation Request (core)
Source File packages/puppeteer-core/src/bidi/core/Request.ts
Repository puppeteer/puppeteer
Lines 349
License Apache-2.0
Copyright 2024 Google Inc.

Overview

Description

The Request class in the bidi/core module is the low-level representation of a network request in the WebDriver BiDi protocol layer. It wraps the raw BiDi network.beforeRequestSent event data and tracks the full lifecycle of a request through response, success, error, redirect, and authentication events. This class sits beneath the high-level BidiHTTPRequest wrapper.

This class extends EventEmitter and emits five events:

  • redirect -- Emitted when the request is redirected, with the new Request object. The current request is disposed after emitting.
  • authenticate -- Emitted when authentication is required (the request is blocked at the auth phase).
  • response -- Emitted when a response starts (network.responseStarted), carrying Bidi.Network.ResponseData.
  • success -- Emitted when the response completes (network.responseCompleted), carrying the most up-to-date ResponseData.
  • error -- Emitted when the request fails (network.fetchError), with the error text string.

Key responsibilities:

  • Request data accessors: Provides url, method, headers, id, initiator, navigation, resourceType, postData, hasPostData, and isBlocked getters. Chrome-specific properties like goog:resourceType, goog:postData, and goog:resourceInitiator are accessed via non-standard BiDi extensions.
  • Redirect chain tracking: Detects redirects by monitoring network.beforeRequestSent events with incremented redirectCount or new authorization headers. Creates new Request objects for each redirect and provides redirect and lastRedirect accessors to walk the chain.
  • Response tracking: Updates the stored response on both network.responseStarted and network.responseCompleted, with the completed event providing the most accurate data (including headers like Set-Cookie for navigation requests).
  • Request interception: continueRequest() continues a blocked request with optional overrides (URL, method, headers, body, cookies). failRequest() fails the request. provideResponse() provides a custom response with status code, reason phrase, headers, and body.
  • Authentication: continueWithAuth() handles authentication challenges by either providing credentials or cancelling.
  • Post data fetching: fetchPostData() retrieves the request body via network.getData with the Request data type. Results are cached.
  • Response content fetching: getResponseContent() retrieves the response body via network.getData with the Response data type. Handles base64-encoded data and provides user-friendly error messages for missing resources.
  • Timing: timing() returns the FetchTimingInfo from the request event, which is updated as response events arrive.
  • Disposal: The request disposes itself after success (for non-redirect responses), error, or redirect events. Listens for the parent browsing context closing to emit an error and dispose.

Usage

This is an internal class not directly used by Puppeteer consumers. It is created by BrowsingContext when network.beforeRequestSent events are received and is wrapped by BidiHTTPRequest.

Code Reference

Source Location

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

Signature

export class Request extends EventEmitter<{
  redirect: Request;
  authenticate: void;
  success: Bidi.Network.ResponseData;
  response: Bidi.Network.ResponseData;
  error: string;
}> {
  static from(
    browsingContext: BrowsingContext,
    event: Bidi.Network.BeforeRequestSentParameters,
  ): Request;

  get disposed(): boolean;
  get error(): string | undefined;
  get headers(): Bidi.Network.Header[];
  get id(): string;
  get initiator(): Bidi.Network.Initiator | undefined;
  get method(): string;
  get navigation(): string | undefined;
  get redirect(): Request | undefined;
  get lastRedirect(): Request | undefined;
  get response(): Bidi.Network.ResponseData | undefined;
  get url(): string;
  get isBlocked(): boolean;
  get resourceType(): string | undefined;
  get postData(): string | undefined;
  get hasPostData(): boolean;

  async continueRequest(
    overrides: Omit<Bidi.Network.ContinueRequestParameters, 'request'>
  ): Promise<void>;
  async failRequest(): Promise<void>;
  async provideResponse(
    params: Omit<Bidi.Network.ProvideResponseParameters, 'request'>
  ): Promise<void>;
  async fetchPostData(): Promise<string | undefined>;
  async getResponseContent(): Promise<Uint8Array>;
  async continueWithAuth(
    parameters: ContinueWithAuthCredentials | ContinueWithAuthNoCredentials
  ): Promise<void>;
  timing(): Bidi.Network.FetchTimingInfo;
}

Import

import {Request} from './core/Request.js';

I/O Contract

Inputs

Parameter Type Description
browsingContext BrowsingContext The browsing context where the request originated
event Bidi.Network.BeforeRequestSentParameters The raw BiDi beforeRequestSent event data

Key Method Parameters

Method Parameter Type Description
continueRequest url string Optional URL override
continueRequest method string Optional method override
continueRequest headers Header[] Optional header overrides
continueRequest body BytesValue Optional body override
provideResponse statusCode number HTTP status code
provideResponse reasonPhrase string HTTP reason phrase
provideResponse headers Header[] Response headers
provideResponse body BytesValue Response body
continueWithAuth action 'cancel' Whether to provide credentials or cancel auth
continueWithAuth credentials {type, username, password} Credentials (when action is provideCredentials)

Outputs

Property/Method Return Type Description
url string The request URL
method string The HTTP method
headers Header[] Request headers as BiDi header objects
id string The request ID
response undefined The response data, or undefined if not yet received
error undefined The error text, or undefined if no error
redirect undefined The next redirect request, if any
lastRedirect undefined The final request in the redirect chain
isBlocked boolean Whether the request is currently blocked for interception
fetchPostData undefined> The request body string
getResponseContent Promise<Uint8Array> The response body as a byte array
timing FetchTimingInfo Fetch timing information

Usage Examples

// Internal usage -- creating a request from a BiDi event
const request = Request.from(browsingContext, beforeRequestSentEvent);

// Listen for request lifecycle events
request.on('response', (responseData) => {
  console.log('Response started:', responseData.status);
});

request.on('success', (responseData) => {
  console.log('Response completed:', responseData.status);
});

request.on('error', (errorText) => {
  console.log('Request failed:', errorText);
});

request.on('redirect', (newRequest) => {
  console.log('Redirected to:', newRequest.url);
});

// Continue a blocked request with modifications
await request.continueRequest({
  url: 'https://modified-url.com',
  headers: [{name: 'x-custom', value: {type: 'string', value: 'test'}}],
});

// Fail a blocked request
await request.failRequest();

// Provide a custom response for a blocked request
await request.provideResponse({
  statusCode: 200,
  reasonPhrase: 'OK',
  headers: [{name: 'content-type', value: {type: 'string', value: 'text/plain'}}],
  body: {type: 'string', value: 'Hello'},
});

// Handle authentication
await request.continueWithAuth({
  action: 'provideCredentials',
  credentials: {type: 'password', username: 'user', password: 'pass'},
});

// Fetch request and response bodies
const postBody = await request.fetchPostData();
const responseBody = await request.getResponseContent();

Related Pages

Page Connections

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