Chrome扩展程序"拒绝加载脚本,因为它违反了以下内容安全策略指令"

Mia*_*Mia 23 html javascript jquery google-chrome google-chrome-extension

我正在尝试创建Chrome扩展程序,但我的JS都没有.控制台显示此错误:

拒绝加载脚本' https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js ',因为它违反了以下内容安全策略指令:"script-src'self'blob :filesystem:chrome-extension-resource:".

为什么阻止我的jQuery运行?

Cha*_*net 15

正如Chome 网站上所述,有一个内容安全策略阻止您的脚本加载远程脚本:

允许通过HTTPS从example.com加载脚本资源的宽松策略定义可能如下所示:

"content_security_policy": "脚本-src的'自我' https://example.com ;对象-src的'自我'"

所以在你的情况下,manifest.json应该包含:

 {
  "name": "My Extension",
  "manifest_version": 2,
  "background":{
     "scripts": [...]
  },
  "content_security_policy": "script-src 'self' https://example.com; object-src 'self'",
 }
Run Code Online (Sandbox Code Playgroud)

  • 那么 example.com 中会发生什么?域名?jquery 文件?你能根据OP的帖子给出一个完整的例子吗? (3认同)
  • @ serv-inc右,"content_security_policy":"script-src'self'https://example.com https://example2.com; object-src'self'",`;`标记最后一个 (2认同)
  • 我收到以下错误:“‘content_security_policy’的值无效。无法加载清单。` ps 清单 3 (2认同)

epa*_*llo 11

您是否在清单JSON文件中允许它.像这样的东西:

的manifest.json

 {
   "name": "My Extension",
   "content_scripts": [{
     "js": ["jquery.min.js", "YourJavaScriptFile.js"],
     "matches": ["http://*/*", "https://*/*"]
   }]
 }
Run Code Online (Sandbox Code Playgroud)

我遗漏了必需的字段,但只是给出了基本的想法.


Sha*_*war 8

我会告诉你长话短说。谷歌浏览器有CSP (Content Security Policy),这意味着 Chrome 扩展不允许外部脚本。如果您正在使用,vue cdn则只需执行以下步骤即可。

  • 在 manifest.json 中添加以下代码并根据需要更改文件名。这里'unsafe-eval'是你正在寻找的东西,只需添加这个。
{
    "manifest_version": 2,
    "name"            : "Hello Extension",
    "version"         : "1.0",
    "permissions": [
        "https://cdn.jsdelivr.net/npm/vue/dist/vue.js"
    ],
    "background": {
        "scripts": ["popup.js"],
        "persistent": false
      },
    "description"     : "Testing the hello world extension",
    "icons": {
        "16"    : "icons16.png",
        "48"    : "icons16.png",
        "128"   : "icons16.png"
    },
    "browser_action": {
        "default_icon"   : "icons16.png",
        "default_popup" : "popup.html"
    },
    "content_security_policy": "script-src 'self' 'unsafe-eval' https://cdn.jsdelivr.net; object-src 'self'"
}
Run Code Online (Sandbox Code Playgroud)
  • 在您external js这里的popup.js 中添加 Vue 代码,一切都会很好。
var app = new Vue({
    el: "#app",
    data: {
        name: ""
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 如何将 content_security_policy 更新为清单 v3...正如很多人所说,会有不同。 (2认同)

Иль*_*шко 5

我找到了这个解决方案

清单V3

"content_security_policy": {
    "extension_pages": "script-src 'self'; object-src 'self'; script-src-elem 'self' 'unsafe-inline' https://music.yandex.ru/;"
}
Run Code Online (Sandbox Code Playgroud)