谷歌浏览器扩展程序制作中的内容安全政策错误

Content-Security-Policy error in google chrome extension making

本文关键字:安全 错误 程序 扩展 谷歌浏览器      更新时间:2023-09-26

我正在制作一个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
}

弹出窗口.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>

背景.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';
}
}

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

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

请帮助我修复这些错误,以便我可以使用我的 chrome 扩展程序在新选项卡中打开所有链接。

"manifest_version": 2的后果之一是默认情况下启用内容安全策略。Chrome 开发人员选择严格要求,并始终禁止内联 JavaScript 代码 - 只允许执行放置在外部 JavaScript 文件中的代码(以防止扩展中的跨站点脚本漏洞)。因此,与其在popup.html中定义getPageandSelectedTextIndex()函数,不如将其放入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);