2015-04-23 94 views
4

我有一个Chrome扩展,我用一个html文件'index.html'覆盖newtab。
我想在此'index.html'上使用jQuery
我该怎么做?在Chrome扩展中重写的新选项卡中使用jQuery违反了内容安全策略?

这里是我的简化代码:

的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://*/" ] 


我该如何解决这个问题?

+2

尝试本地文件版本的jQuery –

+0

在本地文件的情况下,两个错误消失,但$('div')选择器返回空数组。 –

+0

您必须在清单文档中提供权限,检出权限和内容安全策略 –

回答

4

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

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

然而,这是一个更好的做法,包括库的本地副本,您在Chrome扩展使用,而不是依靠CDN。

想象一下,您的新标签页完全无法正确加载,因为连接无法工作,或者由于连接不良而缓慢加载。

1

尝试使用本地文件,并使用$(document).ready()来运行你console.log,该阵列可返回空,因为DOM是没有准备好:

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

这个工作适用于本地托管的jQuery文件。没有外部托管,即https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js –

+2

@AshrafBashir这是ready'和'load'事件之间'的区别;) –

相关问题