CDPEvents in puppeteer

In Puppeteer, CDPEvents refers to events emitted by the Chrome DevTools Protocol (CDP). Puppeteer leverages CDP to interact with and control a Chromium-based browser. CDP provides detailed, low-level access to browser internals, such as network traffic, console logs, page lifecycle events, and more.

You can listen to these CDP events through Puppeteer’s API to monitor or intercept browser activity.


How to Listen for CDP Events in Puppeteer

  1. Enable the Required CDP Domain:
    Some events require enabling a particular domain (e.g., 'Network', 'Page', 'Runtime').

  2. Use page._client() to Access the CDP Session:
    Although it’s a bit lower-level, Puppeteer allows access to DevTools through the page._client() API.


Example: Listening for Network Requests

This example demonstrates how to intercept and log network requests using CDP.

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({ headless: true });
  const page = await browser.newPage();

  // Access the CDP session
  const client = await page.target().createCDPSession();

  // Enable the Network domain to start listening for events
  await client.send('Network.enable');

  // Listen for the 'Network.requestWillBeSent' event
  client.on('Network.requestWillBeSent', (event) => {
    console.log('Request made:', event.request.url);
  });

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

List of Common CDP Domains and Events

Here are some common CDP domains you might use, along with important events:

Domain Key Events Description
Page Page.lifecycleEvent Fires on page lifecycle changes (e.g., load).
Page.javascriptDialogOpening Detects alerts, prompts, or confirms.
Network Network.requestWillBeSent Fired when a request is initiated.
Network.responseReceived Fired when a response is received.
Runtime Runtime.consoleAPICalled Captures console logs (like console.log()).
Runtime.exceptionThrown Fires when an exception is thrown.

When to Use CDP Events?

  • Advanced Monitoring: Use Network events to log requests and analyze responses.
  • Debugging: Use Runtime events to capture logs and exceptions.
  • Automation: Use Page events to handle alerts, popups, and lifecycle events.
  • Performance Profiling: Monitor network traffic and resource loading times.

Accessing CDP Directly vs. Puppeteer Abstractions

  • CDP Events: Provides more control over browser internals.
  • Puppeteer Abstractions: Easier to use for most common cases (e.g., page.on('console')).

In general, use CDP events when you need fine-grained control or when Puppeteer’s high-level APIs don’t expose the functionality you need.

댓글

이 블로그의 인기 게시물

Using the MinIO API via curl

To download a file from MinIO using Spring Boot, 스프링부트 Minio 사용하기

실업급여 받는 방법

훈민정음 1

Joining an additional control plane node to an existing Kubernetes cluster

Install and run an FTP server using Docker

오늘의 문장1

To change the port on a Next.js