CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-puppeteer

A high-level API to control headless Chrome over the DevTools Protocol

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

network-control.mddocs/

Network Control

Request and response interception, network monitoring, and offline mode simulation for comprehensive network testing and debugging.

Capabilities

HTTPRequest Class

Represents HTTP requests with interception and monitoring capabilities.

/**
 * HTTP request with interception capabilities
 */
class HTTPRequest {
  /** Get request URL */
  url(): string;
  
  /** Get HTTP method */
  method(): string;
  
  /** Get request headers */
  headers(): Record<string, string>;
  
  /** Get POST data */
  postData(): string | undefined;
  
  /** Check if request has POST data */
  hasPostData(): boolean;
  
  /** Fetch POST data asynchronously */
  fetchPostData(): Promise<string | undefined>;
  
  /** Get resource type */
  resourceType(): ResourceType;
  
  /** Get initiating frame */
  frame(): Frame | null;
  
  /** Check if navigation request */
  isNavigationRequest(): boolean;
  
  /** Get request initiator */
  initiator(): Protocol.Network.Initiator | undefined;
  
  /** Get redirect chain */
  redirectChain(): HTTPRequest[];
  
  /** Abort request */
  abort(errorCode?: ErrorCode, priority?: number): Promise<void>;
  
  /** Continue request with overrides */
  continue(overrides?: ContinueRequestOverrides, priority?: number): Promise<void>;
  
  /** Mock request response */
  respond(response: Partial<ResponseForRequest>, priority?: number): Promise<void>;
  
  /** Check if interception handled */
  isInterceptResolutionHandled(): boolean;
  
  /** Get associated response */
  response(): HTTPResponse | null;
}

type ResourceType = "document" | "stylesheet" | "image" | "media" | "font" | "script" | "texttrack" | "xhr" | "fetch" | "eventsource" | "websocket" | "manifest" | "other";

type ErrorCode = "aborted" | "accessdenied" | "addressunreachable" | "blockedbyclient" | "blockedbyresponse" | "connectionaborted" | "connectionclosed" | "connectionfailed" | "connectionrefused" | "connectionreset" | "internetdisconnected" | "namenotresolved" | "timedout" | "failed";

interface ContinueRequestOverrides {
  url?: string;
  method?: string;
  postData?: string;
  headers?: Record<string, string>;
}

interface ResponseForRequest {
  status?: number;
  headers?: Record<string, string>;
  body?: string | Uint8Array;
  contentType?: string;
}

Usage Examples:

// Enable request interception
await page.setRequestInterception(true);

page.on("request", async (request) => {
  console.log(`${request.method()} ${request.url()}`);
  
  // Block images
  if (request.resourceType() === "image") {
    await request.abort();
    return;
  }
  
  // Modify headers
  if (request.url().includes("api")) {
    await request.continue({
      headers: {
        ...request.headers(),
        "Authorization": "Bearer token123"
      }
    });
    return;
  }
  
  // Mock response
  if (request.url().includes("config.json")) {
    await request.respond({
      status: 200,
      contentType: "application/json",
      body: JSON.stringify({ mode: "test" })
    });
    return;
  }
  
  await request.continue();
});

HTTPResponse Class

Represents HTTP responses with content access and metadata.

/**
 * HTTP response with content and metadata access
 */
class HTTPResponse {
  /** Get response URL */
  url(): string;
  
  /** Get HTTP status code */
  status(): number;
  
  /** Get status text */
  statusText(): string;
  
  /** Check if status is 200-299 */
  ok(): boolean;
  
  /** Get response headers */  
  headers(): Record<string, string>;
  
  /** Get remote server address */
  remoteAddress(): RemoteAddress;
  
  /** Get TLS security details */
  securityDetails(): SecurityDetails | null;
  
  /** Get timing information */
  timing(): Protocol.Network.ResourceTiming | null;
  
  /** Get raw response body */
  content(): Promise<Uint8Array>;
  
  /** Get response as Buffer */
  buffer(): Promise<Buffer>;
  
  /** Get response as text */
  text(): Promise<string>;
  
  /** Parse response as JSON */
  json(): Promise<any>;
  
  /** Get originating request */
  request(): HTTPRequest;
  
  /** Check if served from cache */
  fromCache(): boolean;
  
  /** Check if served from service worker */
  fromServiceWorker(): boolean;
  
  /** Get associated frame */
  frame(): Frame | null;
}

interface RemoteAddress {
  ip: string;
  port: number;
}

interface SecurityDetails {
  issuer: string;
  validFrom: number;
  validTo: number;
  protocol: string;
  subjectName: string;
  subjectAlternativeNames: string[];
}

Usage Examples:

page.on("response", async (response) => {
  console.log(`${response.status()} ${response.url()}`);
  
  // Check for errors
  if (!response.ok()) {
    console.error(`Failed request: ${response.status()} ${response.statusText()}`);
  }
  
  // Process API responses
  if (response.url().includes("/api/") && response.ok()) {
    try {
      const data = await response.json();
      console.log("API Response:", data);
    } catch (error) {
      console.error("Failed to parse JSON:", error);
    }
  }
  
  // Check security
  const security = response.securityDetails();
  if (security) {
    console.log(`TLS: ${security.protocol}, Issuer: ${security.issuer}`);
  }
});

Network Configuration

Configure network behavior and interception.

/**
 * Enable request interception
 * @param value - Whether to intercept requests
 */
setRequestInterception(value: boolean): Promise<void>;

/**
 * Set offline mode
 * @param enabled - Whether to enable offline mode
 */
setOfflineMode(enabled: boolean): Promise<void>;

/**
 * Set extra HTTP headers
 * @param headers - Headers to add to all requests
 */
setExtraHTTPHeaders(headers: Record<string, string>): Promise<void>;

/**
 * Set authentication credentials
 * @param credentials - HTTP auth credentials or null to disable
 */
authenticate(credentials: Credentials | null): Promise<void>;

interface Credentials {
  username: string;
  password: string;
}

Usage Examples:

// Configure network
await page.setExtraHTTPHeaders({
  "Accept-Language": "en-US,en;q=0.9",
  "User-Agent": "Custom Bot 1.0"
});

// Set authentication
await page.authenticate({
  username: "testuser",
  password: "testpass"
});

// Enable offline mode
await page.setOfflineMode(true);
await page.goto("https://example.com"); // Will fail

await page.setOfflineMode(false);
await page.goto("https://example.com"); // Will succeed

Network Waiting

Wait for specific network events.

/**
 * Wait for request matching predicate
 * @param urlOrPredicate - URL string or predicate function
 * @param options - Wait options
 */
waitForRequest(
  urlOrPredicate: string | ((request: HTTPRequest) => boolean),
  options?: WaitTimeoutOptions
): Promise<HTTPRequest>;

/**
 * Wait for response matching predicate  
 * @param urlOrPredicate - URL string or predicate function
 * @param options - Wait options
 */
waitForResponse(
  urlOrPredicate: string | ((response: HTTPResponse) => boolean),
  options?: WaitTimeoutOptions
): Promise<HTTPResponse>;

/**
 * Wait for network to be idle
 * @param options - Network idle options
 */
waitForNetworkIdle(options?: WaitForNetworkIdleOptions): Promise<void>;

interface WaitTimeoutOptions {
  timeout?: number;
}

interface WaitForNetworkIdleOptions {
  timeout?: number;
  idleTime?: number;
}

Usage Examples:

// Wait for specific requests/responses
const apiRequest = page.waitForRequest("/api/users");
const apiResponse = page.waitForResponse(
  response => response.url().includes("/api/") && response.ok()
);

await page.click("#load-data");

const request = await apiRequest;
const response = await apiResponse;

console.log(`Request: ${request.method()} ${request.url()}`);
console.log(`Response: ${response.status()}`);

// Wait for network idle
await page.goto("https://spa-app.com");
await page.waitForNetworkIdle({ idleTime: 1000 });
console.log("All network requests completed");

Cookie Management

Manage HTTP cookies for network requests.

/**
 * Get cookies for URLs
 * @param urls - URLs to get cookies for (optional)
 */
cookies(...urls: string[]): Promise<Cookie[]>;

/**
 * Set cookies
 * @param cookies - Cookies to set
 */
setCookie(...cookies: CookieParam[]): Promise<void>;

/**
 * Delete cookies
 * @param cookies - Cookies to delete
 */
deleteCookie(...cookies: DeleteCookiesRequest[]): Promise<void>;

interface Cookie {
  name: string;
  value: string;
  domain: string;
  path: string;
  expires?: number;
  size?: number;
  httpOnly?: boolean;
  secure?: boolean;
  session?: boolean;
  sameSite?: "Strict" | "Lax" | "None";
}

interface CookieParam {
  name: string;
  value: string;
  url?: string;
  domain?: string;
  path?: string;
  expires?: number;
  httpOnly?: boolean;
  secure?: boolean;
  sameSite?: "Strict" | "Lax" | "None";
}

interface DeleteCookiesRequest {
  name: string;
  url?: string;
  domain?: string;
  path?: string;
}

Usage Examples:

// Set cookies
await page.setCookie(
  {
    name: "session",
    value: "abc123",
    domain: "example.com"
  },
  {
    name: "preferences",
    value: "dark-mode",
    domain: "example.com",
    httpOnly: true,
    secure: true
  }
);

// Get cookies
const cookies = await page.cookies("https://example.com");
console.log("Page cookies:", cookies);

// Delete cookies
await page.deleteCookie(
  { name: "session", domain: "example.com" },
  { name: "temp-token", domain: "example.com" }
);

Install with Tessl CLI

npx tessl i tessl/npm-puppeteer

docs

browser-management.md

device-emulation.md

element-handling.md

index.md

input-interaction.md

locators-waiting.md

media-generation.md

network-control.md

page-interaction.md

performance-debugging.md

tile.json