chrome 插件开发popup.html引起的报错:Refused to execute inline script because it violates the following Content Security Policy directive

一、问题

popup.html代码如下,导致报错:

<html>
  <body>
    <div id="main_container" style="width:300px;height:300px;background-color: pink;padding: 5px;">
    <button  onclick="test()">test</button>
    </div>
    <script>
      function test(){
        alert("aaa")
      }
    </script>
  </body>
</html>
Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-jVAh+gNjhj7njr2s+2NKsGVVUcQI9KfJAF+lKtF/6FA='), or a nonce ('nonce-...') is required to enable inline execution.

二、原因分析

Chrome扩展程序不允许您使用内联JavaScript。这个错误信息是由于Chrome浏览器的安全策略导致的,具体来说,是因为内联事件处理程序(inline event handler)被拒绝执行,原因是它违反了内容安全策略(Content Security Policy,CSP)。

CSP是一种安全机制,用于帮助检测和减少跨站点脚本攻击(XSS)的风险。当网页中的脚本试图执行不符合CSP规定的代码时,浏览器会拒绝执行这些脚本。

三、问题解决

在pupup.html中引入外部popup.js文件,并在页面加载完成后为按钮添加事件

// popup JS:
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById("click-this").addEventListener("click", function(){
        alert("aaa")
    });
  });

或者这样写:

window.onload = function() {
    document.getElementById("click-this").addEventListener("click", function(){
        alert("bbb")
    });
};
posted @ 2024-05-06 21:39  远洪  阅读(474)  评论(0)    收藏  举报