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

如何在Chrome扩展中修改响应状态码?

能否通过chrome.webRequest修改响应状态码?

明确说:chrome.webRequest本身没法直接修改HTTP响应状态码——这个API只支持修改请求头、响应头,或者拦截、取消请求,但压根没提供修改状态码的接口,这就是你在官方文档里找不到相关内容的原因。

要改状态码,只能走「拦截原请求,返回自定义模拟响应」的路子,具体有两种实现方式:

方案1:用Chrome Declarative Net Request API(Manifest V3推荐)

这是官方现在主推的方案,能直接返回带指定状态码的自定义响应,不用手动折腾拦截取消:

  1. 先在扩展的manifest.json里加权限和规则配置:
{
  "manifest_version": 3,
  "name": "状态码修改工具",
  "version": "1.0",
  "permissions": ["declarativeNetRequest"],
  "host_permissions": ["<all_urls>"],
  "declarative_net_request": {
    "rule_resources": [
      {
        "id": "ruleset_1",
        "enabled": true,
        "path": "rules.json"
      }
    ]
  }
}
  1. 写rules.json定义规则,指定要匹配的URL和自定义响应(包括状态码):
[
  {
    "id": 1,
    "priority": 1,
    "action": {
      "type": "customResponse",
      "statusCode": 404,
      "responseHeaders": [
        {"name": "Content-Type", "value": "text/html; charset=utf-8"}
      ],
      "body": "<h1>自定义404页面</h1>"
    },
    "condition": {
      "urlFilter": "*://example.com/*",
      "resourceTypes": ["main_frame"]
    }
  }
]

这个规则会匹配example.com下的主页面请求,直接返回状态码404和你写的自定义内容,不会把请求发到原服务器。

方案2:拦截原请求手动构造响应(兼容旧版本)

如果要兼容Manifest V2这类旧版本,就用webRequest拦截并取消原请求,再通过脚本往页面里塞自定义响应:

  1. 先在manifest.json里加权限:
{
  "manifest_version": 2,
  "name": "状态码修改工具",
  "version": "1.0",
  "permissions": ["webRequest", "webRequestBlocking", "<all_urls>"],
  "background": {
    "scripts": ["background.js"]
  }
}
  1. 写background.js逻辑:
chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    // 筛选要修改的请求
    if (details.url.includes("example.com")) {
      // 取消原请求
      return {cancel: true};
      // 往目标页面注入脚本,生成自定义响应
      chrome.tabs.executeScript(details.tabId, {
        code: `
          // 构造带指定状态码的响应
          const customResp = new Response("<h1>自定义500错误</h1>", {
            status: 500,
            headers: {"Content-Type": "text/html"}
          });
          // 替换页面内容
          document.open();
          document.write(await customResp.text());
          document.close();
        `
      });
    }
  },
  {urls: ["<all_urls>"]},
  ["blocking"]
);

核心就是先把原请求掐了,再在页面里生成一个带目标状态码的响应,替换掉原本的页面内容。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:30:43