Google Chrome扩展程序制作中的内容安全政策错误

Saa*_*aad 9 javascript google-chrome google-chrome-extension content-security-policy

我正在制作一个Chrome扩展程序,它将在新标签页中打开页面上的所有链接.

这是我的代码文件:

的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
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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';

}
}
Run Code Online (Sandbox Code Playgroud)

最初我想突出显示页面上的所有链接或以某种方式标记它们; 但我收到错误"因内容安全策略而拒绝执行内联脚本".

当我按下弹出窗口内的按钮时,我收到此错误:Refused to execute inline event handler because of Content-Security-Policy.

请帮我修复这些错误,这样我就可以使用我的chrome扩展程序打开新标签中的所有链接.

Wla*_*ant 19

其中一个后果"manifest_version": 2是默认情况下启用了内容安全策略.Chrome开发人员选择严格控制并始终禁止使用内联JavaScript代码 - 只允许执行放置在外部JavaScript文件中的代码(以防止扩展中的跨站点脚本漏洞).因此,不应getPageandSelectedTextIndex()popup.html您中定义函数,而应将其放入popup.js文件并将其包含在popup.html:

<script type="text/javascript" src="popup.js"></script>
Run Code Online (Sandbox Code Playgroud)

并且<button onclick="getPageandSelectedTextIndex()">还必须更改,onclick属性也是内联脚本.您应该分配ID属性:<button id="button">.然后,popup.js您可以将事件处理程序附加到该按钮:

window.addEventListener("load", function()
{
  document.getElementById("button")
          .addEventListener("click", getPageandSelectedTextIndex, false);
}, false);
Run Code Online (Sandbox Code Playgroud)