草庐IT

javascript - Chrome 扩展 "Refused to evaluate a string as JavaScript because ' unsafe-eval'

coder 2023-04-30 原文

我有一个错误:

Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

chrome-extension://ldbpohccneabbobcklhiakmbhoblcpof/popup.html:1

Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".

代码 popup.js

$(document).ready(function() {
     $.getJSON('http://.......alerts.json', function(data) {
        alert('HELLO');
      });
});

list :

{
  "manifest_version": 2,

  "name": "Alert",
  "description": "This extension for  .",
  "version": "2.0",
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
  "permissions": [
    "http://www.......il/"
  ],
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "content_scripts": [ {
    "js": [ "jquery.min.js", "popup.js" ],
    "matches": [ "http://*/*", "https://*/*"]
  }]
}

弹出窗口:

<!doctype html>
<html>
  <head>
    <title>Getting Started Extension's Popup</title>
    <style>
      body {
        min-width: 357px;
        overflow-x: hidden;
      }

      img {
        margin: 5px;
        border: 2px solid black;
        vertical-align: middle;
        width: 75px;
        height: 75px;
      }
    </style>
     <head>
     <script src='jquery.min.js'></script>
     <script src='popup.js'></script>
</head>
  </head>
  <body>
  </body>
</html>

最佳答案

我收到这条消息是因为 Chrome 不再允许内联脚本和内联事件处理程序(如 onClick):必须将它们移动到外部 JS 文件(例如 popup.js)并且必须使用 addEventListener()将事件关联到 DOM 对象。

例如:

<body onload="initialize()">
<button onclick="handleClick()" id="button1">

必须替换为:

window.addEventListener("load", initialize);
document.getElementById("button1").addEventListener("click",handleClick);

在您的情况下,我在 HTML 中看不到任何 JS,但您可以尝试一些事情:

  • 将 popup.js 包含在 .
  • 之前
  • 更正 html(双头)。
  • 从 list 中删除 content_scripts 部分。内容脚本应该针对页面内容执行,它们不是页面或浏览器操作弹出窗口中包含的 JS 文件。浏览器操作部分就足够了。

Chrome extension manifest V2 notes

关于javascript - Chrome 扩展 "Refused to evaluate a string as JavaScript because ' unsafe-eval',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24798669/

有关javascript - Chrome 扩展 "Refused to evaluate a string as JavaScript because ' unsafe-eval'的更多相关文章

随机推荐