无法将 JavaScript 添加到 Chrome 扩展 HTML

4

我想在Chrome扩展程序的弹出窗口中添加一些JavaScript代码。 我使用以下代码:

<!DOCTYPE html>
  <html>
    <head>
      <style>
        button {
          height: 30px;
          width: 30px;
          outline: none;
        }
      </style>
      <script type="text/javascript" src="popup.js"></script> 
    </head>
    <body>
      <button id="ShowButton"></button>
    </body>
  </html>

文件 popup.js 与 html 文件在同一个文件夹中。

我遇到了这个错误:

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

这是我的popup.js内容:
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
    var url = tabs[0].url;
    document.getElementById("ShowButton").value= url;
});

这是manifest.json文件:
    {
 "manifest_version": 2,
 "name": "eRelatorio",
 "description": "Extensão para fazer o relatorio de jogo na plataforma S**ore!",
 "version": "1.0",
 "author": "GoodReferee",
"browser_action": {
   "default_title": "Have a good day",
   "default_popup": "popup.html"
 },
 "icons": { "128": "icon.png" },
"chrome_url_overrides" : {
  "newtab": "newtab.html"
},
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
 "permissions": ["activeTab","tabs"],
 "permissions": [
    "https://www.google.com/"
  ]
}

以下是错误图片:

错误图片


你的代码应该按预期工作... 你的错误报告说你不能直接将脚本写入HTML文件,但实际上你根本没有这样做。 - FZs
你能分享一下 manifest.json 文件吗? - Victor Borshchov
这里根本不需要content_security_policy。错误信息显示你有一个内联js代码,这意味着它可能是由你的完整popup.js添加的,而你在问题中没有展示。简单地不要添加内联js代码,使用事件监听器即可。 - wOxxOm
1个回答

2
尝试将以下代码添加到manifest.json中:
使用unsafe-inline
 "content_security_policy": "script-src 'self' 'unsafe-inline'; object-src 'self'",

更改我的答案 @FábioAraújo - Victor Borshchov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接