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

使用declarativeNetRequests重定向至本地资源失败的解决咨询

问题解决指南

一、图片重定向无效的修复

你的图片重定向配置存在3个核心问题,调整后即可生效:

  1. 补充目标CDN的Host权限
    要拦截https://cdn.example.com/file.jpg的请求,必须在manifest.json的host_permissions中添加该域名:
"host_permissions": [
  "https://www.example.com/*",
  "https://cdn.example.com/*"
]
  1. 修正Web Accessible Resources的匹配规则
    重定向的请求来自CDN域名,需允许该域名访问扩展内的图片资源:
"web_accessible_resources": [
  {
    "resources": ["my_file.jpg"],
    "matches": ["https://cdn.example.com/*"]
  }
]
  1. 声明Declarative Net Request规则集
    在manifest.json中明确指定加载rules.json:
"declarative_net_request": {
  "rulesets": ["rules.json"]
}

调整后的完整manifest.json示例:

{
  "manifest_version": 3,
  "name": "资源重定向扩展",
  "version": "1.0",
  "host_permissions": [
    "https://www.example.com/*",
    "https://cdn.example.com/*"
  ],
  "declarative_net_request": {
    "rulesets": ["rules.json"]
  },
  "web_accessible_resources": [
    {
      "resources": ["my_file.jpg"],
      "matches": ["https://cdn.example.com/*"]
    }
  ]
}

你的rules.json配置无需修改,保持原内容即可。


二、脚本重定向的替代方案

Chrome明确禁止将远程脚本请求重定向到扩展内的JS资源,因此无法用declarativeNetRequest的redirect实现,推荐两种可行方案:

方案1:使用webRequest API拦截重定向(Manifest V3)

通过后台Service Worker拦截请求,直接返回扩展内的脚本:

  1. 在manifest中添加权限
"permissions": ["webRequest", "webRequestBlocking"],
"host_permissions": ["https://site/*"],
"web_accessible_resources": [
  {
    "resources": ["my_script.js"],
    "matches": ["https://site/*"]
  }
]
  1. 后台Service Worker代码(background.js)
chrome.webRequest.onBeforeRequest.addListener(
  (details) => {
    return { redirectUrl: chrome.runtime.getURL("my_script.js") };
  },
  { urls: ["https://site/script1.js"], types: ["script"] },
  ["blocking"]
);

方案2:使用modifyResponse直接替换脚本内容(Chrome 112+)

无需重定向,直接替换远程脚本的响应内容:

在rules.json中添加以下规则:

[
  {
    "id": 1,
    "priority": 10,
    "action": {
      "type": "modifyHeaders",
      "responseHeaders": [
        { "header": "Content-Type", "operation": "set", "value": "application/javascript" }
      ]
    },
    "condition": {
      "urlFilter": "https://site/script1.js",
      "resourceTypes": ["script"]
    }
  },
  {
    "id": 2,
    "priority": 10,
    "action": {
      "type": "modifyResponse",
      "response": {
        "content": "// 这里填入你的修改后脚本内容",
        "encoding": "utf8"
      }
    },
    "condition": {
      "urlFilter": "https://site/script1.js",
      "resourceTypes": ["script"]
    }
  }
]

如果脚本内容较长,可将内容转为Base64编码,设置encoding: "base64"后填入。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:06:22