【问题标题】:How to enable inline execution (chrome extension)如何启用内联执行(chrome 扩展)
【发布时间】:2020-04-22 06:53:52
【问题描述】:

我正在尝试创建一个用于学习目的的 chrome 扩展程序,但由于某种原因我无法通过内容安全策略。当我尝试编写 javascript 内联代码时,我收到一条错误消息,提示我需要使用 sha 哈希或 nonce 来启用我的内联代码的执行。我查看了 chrome 文档并尝试使用我的 content.js 文件的 sha256 哈希,但由于某种原因,我仍然在同一个地方得到相同的错误(错误出现在 popup.html 文件中的查找按钮上)。这是我的清单文件:

{
"manifest_version": 2,
"name": "First Extension",
"version": "0.1",
"browser_action": {
  "default_popup": "popup.html"
},
"permissions": [
  "activeTab"
],
"content_scripts": [
    {
      "matches": [
      "https://*/*"
    ],
    "js": ["content.js"]
  }
],
"content_security_policy": "default-src 'self'; script-src 'self' <my domain> 'sha256-<hash of content.js in sha256, base 64>'; style-src * 'unsafe-inline'; img-src 'self' data:; connect-src <my domain>;"
}

我的 popup.html 文件:

<!doctype html>
<html>
  <head>
    <title>Yelp Popup</title>
      <script src = "content.js"></script>
  </head>

  <body>
    <div style = "height: 500px; width: 300px;">
      <h1>Find yelp reviews</h1>
      <button>Find</button>
    </div>
  </body>

</html>

还有我的 content.js 文件:

function getReviews() {
fetch(<my domain>)
  .then((response) => {
  return response.json();
})
  .then((myJson) => {
  console.log(myJson);
});
}

document.addEventListener('DOMContentLoaded', function() {
    document.querySelector('button').addEventListener('click', getReviews);
});

我对此很陌生,因此我们将不胜感激任何帮助/建议。关于如何使用 sha 哈希将我的代码列入白名单,我一定缺少一些东西,但我已经多次查看 chrome 扩展文档,但仍然无法弄清楚它是什么。

【问题讨论】:

标签: javascript google-chrome-extension


【解决方案1】:

您正在查看错误的控制台:chrome://extensions 页面上的错误列表不会自动清除,它会累积所有错误,直到您在 UI 中手动清除列表。

  1. browser_action 弹出窗口是一个单独的窗口,因此它有一个单独的控制台:在弹出窗口内右键单击,然后单击“检查”

  2. browser_action 弹出窗口也是一个单独的 document + window 与浏览器选项卡中的网页无关,因此在此处使用不同的 js 文件:例如 popup.js。

    相关:How to access the webpage DOM rather than the extension page DOM

  3. 删除 content_scripts 部分

  4. 删除 content_security_policy 部分并使用单独的 popup.js,more info

  5. 要在扩展弹出窗口的上下文中获取 URL,它有自己的 chrome-extension:// URL,您需要在“权限”中为 &lt;my domain&gt; 添加一个有效的 URL pattern,请参阅 Cross-Origin XMLHttpRequest在扩展文档中。

【讨论】:

    猜你喜欢
    • 2018-12-03
    • 1970-01-01
    • 2014-10-26
    • 1970-01-01
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    相关资源
    最近更新 更多