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:Microsoft Playwright Page Network Events

From Leeroopedia
Knowledge Sources
Domains Network_Testing, Mocking, Traffic_Analysis
Last Updated 2026-02-11 00:00 GMT

Overview

Concrete tool for monitoring network traffic and identifying interception targets provided by the Playwright library.

Description

Playwright exposes network lifecycle events on the Page object that allow tests to observe every HTTP request and response flowing through the browser. These events are the primary mechanism for identifying which network calls an application makes, enabling informed decisions about what to mock or intercept.

The Page class emits four network-related events, defined in packages/playwright-core/src/client/events.ts:L57-79:

  • request -- Emitted when a network request is initiated. Provides a Request object with URL, method, headers, resource type, and post data.
  • response -- Emitted when a response is received for a request. Provides a Response object with status code, headers, and body access methods.
  • requestfailed -- Emitted when a request fails (network error, DNS failure, aborted).
  • requestfinished -- Emitted when a request finishes and its response body has been fully received.

The event subscription mapping is configured in the Page constructor at packages/playwright-core/src/client/page.ts:L160-168, which maps client-side event names to server-side channel subscription parameters. This ensures the browser only sends network events when listeners are actually registered, optimizing performance.

The Request class (packages/playwright-core/src/client/network.ts:L86-297) provides rich introspection methods: url(), method(), resourceType(), postData(), headers(), allHeaders(), response(), frame(), isNavigationRequest(), and timing().

The Response class (packages/playwright-core/src/client/network.ts:L636-744) provides: url(), ok(), status(), statusText(), headers(), allHeaders(), body(), text(), json(), request(), frame(), serverAddr(), and securityDetails().

Usage

Use page network events when:

  • You need to understand which API endpoints a page calls during a specific user flow.
  • You want to log all network traffic for debugging purposes.
  • You need to identify requests to third-party services that should be blocked or mocked.
  • You want to collect request/response data for later assertion.
  • You are building a custom network monitoring tool on top of Playwright.

Code Reference

Source Location

  • Repository: playwright
  • Events definition: packages/playwright-core/src/client/events.ts:L57-79
  • Subscription mapping: packages/playwright-core/src/client/page.ts:L160-168
  • Request class: packages/playwright-core/src/client/network.ts:L86-297
  • Response class: packages/playwright-core/src/client/network.ts:L636-744

Signature

// Event subscription
page.on(event: 'request', callback: (request: Request) => void): void;
page.on(event: 'response', callback: (response: Response) => void): void;
page.on(event: 'requestfailed', callback: (request: Request) => void): void;
page.on(event: 'requestfinished', callback: (request: Request) => void): void;

// Request class key methods
class Request {
  url(): string;
  method(): string;
  resourceType(): string;
  postData(): string | null;
  postDataJSON(): object | null;
  postDataBuffer(): Buffer | null;
  headers(): Record<string, string>;
  allHeaders(): Promise<Record<string, string>>;
  headersArray(): Promise<Array<{name: string, value: string}>>;
  response(): Promise<Response | null>;
  frame(): Frame;
  isNavigationRequest(): boolean;
  timing(): ResourceTiming;
  redirectedFrom(): Request | null;
  redirectedTo(): Request | null;
  failure(): { errorText: string } | null;
  serviceWorker(): Worker | null;
}

// Response class key methods
class Response {
  url(): string;
  ok(): boolean;
  status(): number;
  statusText(): string;
  headers(): Record<string, string>;
  allHeaders(): Promise<Record<string, string>>;
  body(): Promise<Buffer>;
  text(): Promise<string>;
  json(): Promise<object>;
  request(): Request;
  frame(): Frame;
  fromServiceWorker(): boolean;
  serverAddr(): Promise<RemoteAddr | null>;
  securityDetails(): Promise<SecurityDetails | null>;
  finished(): Promise<null>;
}

Import

// Playwright Test (recommended)
import { test, expect } from '@playwright/test';

// Library mode
import { chromium, Request, Response } from 'playwright';

I/O Contract

Inputs

Name Type Required Description
event string Yes Event name: 'request', 'response', 'requestfailed', or 'requestfinished'
callback Function Yes Callback receiving the emitted Request or Response object

Outputs

Name Type Description
Request Request Emitted for 'request', 'requestfailed', and 'requestfinished' events; contains URL, method, headers, resource type, post data, timing, and navigation status
Response Response Emitted for 'response' event; contains URL, status, headers, and methods to read the body as Buffer, text, or JSON

Usage Examples

Basic Example

import { test, expect } from '@playwright/test';

test('log all network requests', async ({ page }) => {
  // Listen for all requests
  page.on('request', request => {
    console.log(`>> ${request.method()} ${request.url()} [${request.resourceType()}]`);
  });

  // Listen for all responses
  page.on('response', response => {
    console.log(`<< ${response.status()} ${response.url()}`);
  });

  // Listen for failed requests
  page.on('requestfailed', request => {
    console.log(`FAILED: ${request.url()} ${request.failure()?.errorText}`);
  });

  await page.goto('https://example.com');
});

Filtering by Resource Type

import { test, expect } from '@playwright/test';

test('identify API calls for mocking', async ({ page }) => {
  const apiCalls: string[] = [];

  page.on('request', request => {
    // Only track XHR and fetch requests (API calls)
    if (request.resourceType() === 'xhr' || request.resourceType() === 'fetch') {
      apiCalls.push(`${request.method()} ${request.url()}`);
    }
  });

  await page.goto('https://example.com/dashboard');
  await page.waitForLoadState('networkidle');

  // Now apiCalls contains all API endpoints called during page load
  console.log('API calls to mock:', apiCalls);
});

Collecting Response Data

import { test, expect } from '@playwright/test';

test('inspect response payloads', async ({ page }) => {
  page.on('response', async response => {
    if (response.url().includes('/api/')) {
      const body = await response.json().catch(() => null);
      console.log(`API Response: ${response.url()}`, {
        status: response.status(),
        ok: response.ok(),
        body: body,
      });
    }
  });

  await page.goto('https://example.com/dashboard');
});

Using page.requests() Snapshot

import { test, expect } from '@playwright/test';

test('get snapshot of all requests', async ({ page }) => {
  await page.goto('https://example.com');

  // page.requests() returns a snapshot of all tracked requests
  const allRequests = await page.requests();
  const apiRequests = allRequests.filter(
    r => r.url().includes('/api/')
  );

  console.log(`Total requests: ${allRequests.length}`);
  console.log(`API requests: ${apiRequests.length}`);
});

Related Pages

Implements Principle

Page Connections

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