9

新しいタブでページのすべてのリンクを開くChrome拡張機能を作成しています。最初は私がすべて強調表示したかったGoogle Chromeの拡張機能でContent-Security-Policyエラーが発生する

manifest.jsonを

{ 
    "name": "A browser action which changes its icon when clicked.", 
    "version": "1.1", 
    "permissions": [ 
    "tabs", "<all_urls>" 
    ], 
"browser_action": {  
    "default_title": "links",  // optional; shown in tooltip 
    "default_popup": "popup.html"  // optional 
    }, 
"content_scripts": [ 
    { 
    "matches": [ "<all_urls>" ], 
     "js": ["background.js"] 
    } 
    ], 
    "manifest_version": 2 
} 

popup.html

<!doctype html> 
<html> 
    <head> 
    <title>My Awesome Popup!</title> 
    <script> 
function getPageandSelectedTextIndex() 
    { 
    chrome.tabs.getSelected(null, function(tab) { 
    chrome.tabs.sendRequest(tab.id, {greeting: "hello"}, function (response) 
    { 
     console.log(response.farewell); 
    }); 
    }); 
     } 
chrome.browserAction.onClicked.addListener(function(tab) { 
     getPageandSelectedTextIndex(); 
}); 
     </script> 
    </head> 
    <body> 
    <button onclick="getPageandSelectedTextIndex()"> 
     </button> 
    </body> 
</html> 

background.js

chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) { 
    console.log(sender.tab ? 
       "from a content script:" + sender.tab.url : 
       "from the extension"); 
    if (request.greeting == "hello") 
    updateIcon(); 

}); 
function updateIcon() { 
    var allLinks = document.links; 
    for (var i=0; i<allLinks.length; i++) { 
    alllinks[i].style.backgroundColor='#ffff00'; 

} 
} 

:ここ

は私のコードファイルですtのリンク彼は何らかの方法でページングしたりマークしたりする。 「コンテンツセキュリティポリシーのためにインラインスクリプトを実行するのが拒否されました」というエラーが表示されます。

ポップアップ内のボタンを押すと、私はこのエラーを受け取ります:Refused to execute inline event handler because of Content-Security-Policy

私はこれらのエラーを解決するために、私のクロムエクステンションを使用して新しいタブですべてのリンクを開くことができます。

答えて

18

の結果の1つは、デフォルトではContent Security Policyが有効になっていることです。また、Chrome開発者は厳密にすることを選択し、常にインラインJavaScriptコードを禁止しました。外部JavaScriptファイルに配置されたコードのみを実行できます(拡張子はCross-Site Scripting vulnerabilities)。だからではなく、popup.htmlgetPageandSelectedTextIndex()関数を定義するのあなたはpopup.jsファイルにそれを置く必要があるとpopup.htmlに含める:

<script type="text/javascript" src="popup.js"></script> 

そして<button onclick="getPageandSelectedTextIndex()">も同様に変更する必要があり、onclick属性もインラインスクリプトです。代わりにID属性を割り当てる必要があります。<button id="button">。次に、popup.jsで、そのボタンにイベントハンドラをアタッチできます。

window.addEventListener("load", function() 
{ 
    document.getElementById("button") 
      .addEventListener("click", getPageandSelectedTextIndex, false); 
}, false); 
+0

ちょうど私にそれを打つ。パーフェクトな答えは、あなたがする必要があるものです。 – Alasdair

+0

kありがとう..iそれを試してみます – Saad

+0

これはとても馬鹿です。誰がこのアイデアを思いついたのですか?今度はすべてのインラインonclicksを変更して、それらを外部のjsファイルに入れなければなりません。そして、私はそれらを含むファイルの束を持っています。 –

関連する問題