2015-04-23 45 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'事件之間'的區別;) –

相關問題