Chrome扩展程序拒绝加载外部脚本

4
我正在使用manifest版本3构建Chrome扩展程序。整个扩展程序的目的是将外部动态脚本注入到页面中(例如,https://example.com/)。但我一直收到以下消息:
Refused to load the script 'https://example.com/' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.
我试图在我的清单文件中添加content_security_policy条目,但似乎无法使其工作。假设我加载的这个脚本将从不同的域调用多个其他脚本,有什么方法可以启用它?

3
ManifestV3 的设计禁止远程脚本。 - wOxxOm
3个回答

4

清单 V2

在Chrome扩展中,您可以像这样使用清单V2:

manifest.json

"content_security_policy": "script-src 'self' https://example.com/; 

清单 V3

远程托管的代码

在清单 V3 中,您的扩展程序的所有逻辑必须与扩展程序捆绑在一起。您不能再加载和执行远程托管的文件。根据您的用例和远程托管的原因,有许多替代方法可供选择。

来源: https://developer.chrome.com/docs/extensions/mv3/intro/mv3-migration/#remotely-hosted-code


1

Manifest v3方法

我找不到一种包含远程脚本的方法,但如果您可以下载外部JS文件并将其作为扩展的一部分放置,它将与扩展代码捆绑在一起,并且您可以使用相对URL在内容脚本中引用它。以下是如何操作。

假设您已经下载并将example.js与您的内容脚本文件放在一起。在您的manifest.json中,将该文件添加到web_accessible_resources中。

web_accessible_resources: [
  ...
  {
    resources: ['example.js'],
    matches: ['*://*/*'],
  },
],

接下来,将以下代码添加到您的内容脚本中。
const inject = () => {
  var r = document.createElement('script');
  r.setAttribute('src', 'chrome-extension://' + chrome.runtime.id + '/example.js');
  (document.head || document.documentElement).appendChild(r);
};

inject();

请注意,一旦包含上述代码的内容脚本运行,example.js文件将立即被注入并执行。此外,请确保如果您有类似webpack的捆绑工具,则需要配置它以将JS文件包含在最终打包文件中。

0
你可以使用declarativeNetRequest API来添加一个规则,以修改CSP头部为你需要的格式,从而接受该脚本。例如,像这样:
{
    "id": 11,
    "priority": 1,
    "action": {
        "type": "modifyHeaders",
        "responseHeaders": [
            { "header": "Content-Security-Policy", "operation": "append", "value": "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://example.com" }
        ]
    },
    "condition": { "urlFilter": "my-domain.com", "resourceTypes": ["sub_frame"] }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接