Home  Puppeteer   How chrome ...

how chrome dev protocol works

The Chrome DevTools Protocol (CDP) facilitates communication between a client (such as an automation script or a debugging tool) and the Chrome browser. Here’s how CDP creates a WebSocket connection within the Chrome process:

Overview of CDP WebSocket Setup

  1. Starting Chrome with Remote Debugging Enabled:

    • To use CDP, Chrome must be started with remote debugging enabled. This is typically done by launching Chrome with the --remote-debugging-port=<port> command-line option.
    • Example:
      chrome --remote-debugging-port=9222
      
  2. WebSocket Endpoint in Chrome:

    • When Chrome is started with remote debugging, it opens a WebSocket endpoint internally. This endpoint is accessible via a URL that includes the port specified (9222 in the example).
  3. WebSocket URL Format:

    • The WebSocket URL format to connect to Chrome's DevTools Protocol looks like:
      ws://localhost:<port>/devtools/browser/<session-id>
      
    • <port> is the port number specified with --remote-debugging-port.
    • <session-id> is a unique identifier for the debugging session.
  4. Connecting to Chrome's CDP:

    • Clients (such as automation scripts or debugging tools) connect to Chrome's CDP using the WebSocket URL.
    • Example WebSocket connection in JavaScript:
      const WebSocket = require('ws');
      
      const ws = new WebSocket('ws://localhost:9222/devtools/browser/<session-id>');
      
      ws.on('open', () => {
        console.log('Connected to Chrome CDP');
      });
      
      ws.on('message', (message) => {
        console.log('Received message from Chrome:', message);
      });
      
      ws.on('close', () => {
        console.log('Connection closed');
      });
      
      ws.on('error', (error) => {
        console.error('WebSocket error:', error);
      });
      
  5. Communication via JSON-RPC:

    • Communication between the client and Chrome over the WebSocket follows the JSON-RPC (Remote Procedure Call) protocol.
    • Clients send commands (JSON objects) to Chrome, specifying methods like Page.navigate, Runtime.evaluate, etc.
    • Chrome responds with JSON objects containing results or events related to the command.
  6. Lifecycle of WebSocket Connection:

    • The WebSocket connection remains open as long as the debugging session in Chrome is active.
    • When Chrome is closed or the debugging session ends, the WebSocket connection is terminated.

How CDP Creates WebSocket Within Chrome

Inside the Chrome browser process, the steps involved in creating the WebSocket for CDP include:

Key Points

Published on: Jun 27, 2024, 11:18 PM  
 

Comments

Add your comment