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

Chrome扩展declarative_net_request重定向XMLHttpRequest问题求助

问题:Chrome扩展Declarative Net Request无法重定向POST请求

开发Chrome扩展时遇到问题:无法将发往https://api.old.com/endpoint的POST类型REST API请求重定向至https://api.new.com/newapi,且onRuleMatchedDebug事件从未触发,求解决思路。

相关代码文件

manifest.json

{
  "name": "Foo",
  "version": "1.0",
  "manifest_version": 3,
  "declarative_net_request": {
    "rule_resources": [
      {
        "id": "ruleset_1",
        "enabled": true,
        "path": "rules_1.json"
      }
    ]
  },
  "permissions": [
    "declarativeNetRequest",
    "declarativeNetRequestFeedback",
    "declarativeNetRequestWithHostAccess"
  ],
  "background": {
    "service_worker": "serviceWorker.js"
  },
  "host_permissions": ["https://api.old.com/*", "https://api.new.com/*"]
}

rules_1.json

[
  {
    "id": 1,
    "action": {
      "type": "redirect",
      "redirect": {
        "url": "https://api.new.com/newapi"
      }
    },
    "condition": {
      "urlFilter": "https://api.old.com/endpoint",
      "resourceTypes": ["xmlhttprequest"],
      "requestMethods": ["post"]
    }
  }
]

Service Worker(serviceWorker.js)

'use strict';

chrome.declarativeNetRequest.onRuleMatchedDebug.addListener((e) => {
  const msg = `Navigation to ${e.request.url} redirected on tab ${e.request.tabId}.`;
  console.log(msg, e);
});

console.log('Service worker started!.');

排查与解决思路

  • 修正URL匹配规则:
    Declarative Net Request的urlFilter默认是前缀匹配,如果目标请求带有查询参数(如https://api.old.com/endpoint?param=1)或末尾斜杠(https://api.old.com/endpoint/),当前规则会匹配失败。可以调整规则:

    • 若需精确匹配无参数的URL,添加"matchType": "exact"到condition中;
    • 若需匹配所有包含该路径的请求,将urlFilter改为*://api.old.com/endpoint*。
  • 扩展resourceTypes覆盖范围:
    部分fetch请求可能被归类为xmlhttprequest,但为避免遗漏,可将resourceTypes改为["xmlhttprequest", "fetch"]。

  • 统一请求方法大小写:
    尝试将requestMethods改为大写"POST",排除潜在的大小写匹配问题。

  • 验证扩展权限状态:
    进入chrome://extensions/页面,确认扩展已被授予host_permissions对应的网站访问权限,开发模式下需确保未被浏览器限制。

  • 查看Chrome内置日志排查:

    1. 打开扩展的后台页面,确认service worker正常启动(能看到Service worker started!.日志);
    2. 访问chrome://net-internals/#events,搜索declarative_net_request事件,查看规则是否加载成功、请求是否触发匹配逻辑。
  • 检查规则ID唯一性:
    确保rules_1.json中的规则ID(当前为1)未与其他规则集的ID重复,重复ID会导致规则失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 12:16:01