79820438

Date: 2025-11-14 21:04:14
Score: 1
Natty:
Report link

How to Intercept Network Traffic in a Chrome Extension Using chrome.debugger API

Overview

The chrome.debugger API allows Chrome extensions to interact with the Chrome DevTools Protocol (CDP), enabling network traffic interception. This is useful for monitoring, logging, or modifying network requests and responses in real-time.

Step-by-Step Tutorial

1. Manifest Permissions

Ensure your manifest.json includes the necessary permissions:

{
  "manifest_version": 3,
  "name": "Network Traffic Interceptor",
  "version": "1.0",
  "permissions": ["debugger", "storage"],
  "host_permissions": ["https://www.google.com/*"],
  "background": {
    "service_worker": "service-worker.js"
  },
  "action": {}
}

2. Attach Debugger to Tab

In your service worker (service-worker.js), attach the debugger to the active tab:

async function attachDebugger(tab) {
  if (!tab || !tab.id) return;
  if (!tab.url.startsWith("http")) {
    console.error("Debugger can only be attached to HTTP/HTTPS pages.");
    return;
  }

  const debuggee_id = { tabId: tab.id };

  try {
    await chrome.debugger.detach(debuggee_id);
  } catch (e) {
    // Ignore if not attached
  }

  try {
    await chrome.debugger.attach(debuggee_id, "1.3"); // https://chromedevtools.github.io/devtools-protocol/
    await chrome.debugger.sendCommand(debuggee_id, "Network.enable", {});
    console.log("Network interception enabled.");
  } catch (error) {
    console.error("Failed to attach debugger:", error);
  }
} // Google's boilerplates: https://github.com/GoogleChrome/chrome-extensions-samples/blob/main/api-samples/

// usage: Attach on action click
chrome.action.onClicked.addListener(async (tab) => {
  await attachDebugger(tab);
});

3. Listen for Network Events

Set up event listeners for network events:

const pending_requests = new Map();

chrome.debugger.onEvent.addListener(function (source, method, params) {
  if (method === "Network.responseReceived") {
    // Store request ID for later retrieval
    pending_requests.set(params.requestId, params.response.url);
  }

  if (method === "Network.loadingFinished") {
    const request_id = params.requestId;
    const url = pending_requests.get(request_id);
    if (!url) return;
    pending_requests.delete(request_id);

    chrome.debugger.sendCommand(
      source,
      "Network.getResponseBody",
      { requestId: request_id },
      function (result) {
        if (chrome.runtime.lastError) {
          console.error(
            `Failed to get response body: ${chrome.runtime.lastError.message}`
          );
          return;
        }
        if (result && result.body) {
          const body = result.base64Encoded ? atob(result.body) : result.body;
          console.log(`Response from ${url}:`, body);
          // Process the response body here
        }
      }
    );
  }
});

Running the Extension

  1. Create a new directory for your extension.
  2. Save the manifest.json and service-worker.js files as shown above.
  3. Load the directory as an unpacked extension in Chrome:
    • Open chrome://extensions/.
    • Enable "Developer mode".
    • Click "Load unpacked" and select your directory.
  4. Navigate to an HTTP/HTTPS webpage (e.g., https://stackoverflow.com/questions).
  5. Click the extension's action button (puzzle piece icon) to attach the debugger.
  6. Open the developer console (F12) to see logged network responses.
  7. Interact with the page to trigger network requests and observe the logs.

Handling the "{"code":-32000,"message":"No resource with given identifier found"}" Error

This error stems from Network.getResponseBody and is symptomatic of the following common causes:

Mitigation:

Network Protocols and Event Flow

Underlying Changes in Network Domain

The Network domain manages an in-memory buffer for response bodies. Enabling resets this buffer, ensuring fresh state but invalidating old data.

Relevant Sources

Reasons:
  • Blacklisted phrase (1): stackoverflow
  • Long answer (-1):
  • Has code block (-0.5):
  • Starts with a question (0.5): How to In
  • Low reputation (1):
Posted by: KevinS