在覆盖的新选项卡中使用 jQuery,在 Chrome 扩展中,是否违反了内容安全策略?

Using jQuery in overridden new tab, in Chrome Extension, violates Content Security Policy?

我有一个 chrome 扩展,我用 html 文件覆盖了新标签 'index.html'。
我想在这个上使用 jQuery 'index.html'
我该怎么做?

这是我的简化代码:

manifest.json

{
    "name": "Test Name",
    "description": "Test Description",
    "version": "0.1",
    "chrome_url_overrides": {
        "newtab": "index.html"
    },
    "manifest_version": 2,
}


index.html

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script src="index.js"></script>
    </head>
    <body>
        <div> Hello World ! </div>
    </body>
</html>


index.js

console.log('Extension loaded successfully ...');
console.log($('div')); // console.log(jQuery('div'));


但是我在控制台中不断收到以下两个错误。

Refused to load the script 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js' because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".

Extension loaded successfully ...

Uncaught ReferenceError: $ is not defined


更新:1 我也尝试在清单文件中添加 content security policy,但它不起作用,并且仍然产生错误:

"content_security_policy": "script-src 'self' https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js 'unsafe-eval'; object-src 'self'",


更新:2 我也尝试在清单文件中添加权限,但它也不起作用,仍然是同样的错误:

"permissions": [ "http://*/", "https://*/" ]


我该如何解决这个问题?

尝试使用本地文件并使用 $( document ).ready() 到 运行 您的 console.log,数组可能返回空,因为 DOM 尚未准备好:

$(document).ready(function(){
    console.log($('div'));
})

您使用的 CSP 字符串格式有误。正确的应该是(注意没有路径):

"content_security_policy": "script-src 'self' https://ajax.googleapis.com 'unsafe-eval'; object-src 'self'"

但是,更好的做法是包含您在 Chrome 扩展中使用的库的本地副本,而不是依赖 CDN。

假设您的新标签页完全无法正常加载,因为连接不工作,或者由于连接不佳而加载缓慢。