10

ページ上のすべてのリンクを新しいタブで開くChrome拡張機能を作成しています。

これが私のコードファイルです:

マニフェスト.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';

}
}

最初は、ページ上のすべてのリンクを強調表示するか、何らかの方法でそれらにマークを付けたいと思いました。しかし、「Content-Security-Policyのためにインラインスクリプトの実行を拒否しました」というエラーが表示されます。

ポップアップ内のボタンを押すと、次のエラーが発生しますRefused to execute inline event handler because of Content-Security-Policy

Chrome拡張機能を使用して新しいタブですべてのリンクを開くことができるように、これらのエラーを修正するのを手伝ってください。

4

1 に答える 1

22

の結果の1つは"manifest_version": 2コンテンツセキュリティポリシーがデフォルトで有効になっていることです。また、Chrome開発者はこれを厳しくし、インラインJavaScriptコードを常に禁止することを選択しました。外部JavaScriptファイルに配置されたコードのみが実行を許可されます(拡張機能のクロスサイトスクリプティングの脆弱性を防ぐため)。getPageandSelectedTextIndex()したがって、関数を定義する代わりに、それをファイルpopup.htmlに入れて、次のように含める必要があります。popup.jspopup.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);
于 2012-06-15T06:45:35.057 に答える