You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在Manifest V3版Chrome扩展中用declarativeNetRequest拦截JSON响应?

在Chrome扩展Manifest V3中读取特定网站XHR请求的JSON数据

当然可行,但需要明确:declarativeNetRequest本身无法直接读取响应内容,它主要用于修改请求/响应头、拦截请求等场景。要获取XHR的JSON响应数据,通常需要结合其他API实现,下面是两种常用方案:

方案一:后台服务Worker结合webRequest API(适合后台处理数据)

此方案在扩展后台直接拦截请求并重新获取响应数据,适合无需页面交互的场景。

1. 配置manifest.json

声明必要权限和主机匹配规则:

{
  "manifest_version": 3,
  "name": "XHR数据读取工具",
  "version": "1.0",
  "permissions": ["webRequest"],
  "host_permissions": ["https://目标网站域名/*"], // 替换为实际目标网站
  "background": {
    "service_worker": "background.js"
  }
}

2. 编写background.js逻辑

监听请求完成事件,过滤目标XHR并重新获取响应:

chrome.webRequest.onCompleted.addListener(
  async (details) => {
    // 过滤目标接口,比如根据URL路径判断
    if (details.url.includes("/api/目标接口路径")) {
      try {
        // 重新发起请求获取响应体(webRequest无法直接读取响应内容)
        const response = await fetch(details.url, {
          headers: details.requestHeaders,
          credentials: "include"
        });
        const jsonData = await response.json();
        // 在这里处理数据,比如存储、分析
        console.log("获取到的JSON数据:", jsonData);
      } catch (error) {
        console.error("读取响应失败:", error);
      }
    }
  },
  { urls: ["https://目标网站域名/*"] },
  ["responseHeaders"]
);

方案二:注入内容脚本监听XHR/fetch(适合页面上下文处理)

通过注入内容脚本重写XHR或fetch方法,直接在页面上下文拦截响应数据,适合需要和页面交互的场景。

1. 配置manifest.json

声明脚本注入权限和匹配规则:

{
  "manifest_version": 3,
  "name": "XHR数据读取工具",
  "version": "1.0",
  "permissions": ["scripting"],
  "host_permissions": ["https://目标网站域名/*"],
  "content_scripts": [
    {
      "matches": ["https://目标网站域名/*"],
      "js": ["content.js"],
      "run_at": "document_start"
    }
  ]
}

2. 编写content.js逻辑

重写XHR和fetch方法,拦截响应并处理:

// 拦截XMLHttpRequest
const originalXhrOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) {
  if (url.includes("/api/目标接口路径")) {
    this.addEventListener("load", () => {
      try {
        const jsonData = JSON.parse(this.responseText);
        console.log("拦截到XHR响应:", jsonData);
        // 可通过消息把数据传给后台
        chrome.runtime.sendMessage({ type: "XHR_DATA", data: jsonData });
      } catch (e) {
        console.error("解析响应失败:", e);
      }
    });
  }
  return originalXhrOpen.apply(this, arguments);
};

// 拦截fetch请求
const originalFetch = window.fetch;
window.fetch = async function(resource) {
  const response = await originalFetch.apply(this, arguments);
  if (typeof resource === "string" && resource.includes("/api/目标接口路径")) {
    // 克隆响应(响应流只能读取一次)
    const clonedResp = response.clone();
    const jsonData = await clonedResp.json();
    console.log("拦截到fetch响应:", jsonData);
    chrome.runtime.sendMessage({ type: "FETCH_DATA", data: jsonData });
  }
  return response;
};

3. 后台接收数据(可选)

如果需要在后台处理数据,在background.js中监听消息:

chrome.runtime.onMessage.addListener((message) => {
  if (message.type === "XHR_DATA" || message.type === "FETCH_DATA") {
    console.log("后台收到数据:", message.data);
    // 后续处理:存储到chrome.storage或进行分析
  }
});

declarativeNetRequest的辅助作用

虽然它不能直接读取响应,但可以给目标请求添加自定义标识,方便内容脚本更精准识别:

  1. 在manifest.json中添加规则配置:
{
  "declarative_net_request": {
    "rule_resources": [
      {
        "id": "ruleset_1",
        "enabled": true,
        "path": "rules.json"
      }
    ]
  }
}
  1. 编写rules.json,给目标请求添加自定义请求头:
[
  {
    "id": 1,
    "priority": 1,
    "action": {
      "type": "modifyHeaders",
      "requestHeaders": [
        { "operation": "set", "header": "X-My-Extension", "value": "true" }
      ]
    },
    "condition": {
      "urlFilter": "/api/目标接口路径",
      "domains": ["目标网站域名"],
      "resourceTypes": ["xmlhttprequest", "fetch"]
    }
  }
]

之后内容脚本可以通过检查请求头中的X-My-Extension字段,更准确地定位目标请求。

内容的提问来源于stack exchange,提问作者dani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 01:32:34