【问题标题】:Chrome extension cant run a fetch request because it violets CSPChrome 扩展程序无法运行获取请求,因为它违反了 CSP
【发布时间】:2021-03-17 12:40:09
【问题描述】:

我正在开发一个 chrome 扩展程序,它确实可以在本地工作,但是在作为 chrome 扩展程序启动时会出现以下错误:

Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' https://apis.google.com". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

我的清单文件是:

{
  "manifest_version": 2,
  "name": "Fake News Launcher",
  "description": "Check the integrity of news!",
  "version": "1.1.0",
  "icons": {
    "128": "icon_128.png"
  },
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "index.html"
  },
  "permissions": [
    "activeTab"
  ]
}

我尝试添加 "content_security_policy":"script-src 'self' https://apis.google.com; object-src 'self'" 但这并没有解决问题

导致错误的函数是

async function onTestChange() {
  let key = window.event.keyCode;
  let string = $(".fact-input").val();
  //! If the user has pressed enter
  if (key === 13) {
    try {
      const res = await fetch("http://127.0.0.1:5000/create/", {
        method: "POST",
        body: JSON.stringify({
          string,
        }),
        headers: {
          "Content-Type": "application/json",
        },
      });
      const data = await res.json();
      loadingbar(parseInput(data));
    } catch (err) {
      console.log(err);
    }
  }
}

【问题讨论】:

  • 与其尝试启用内联执行,为什么不直接将代码移动到 .js 文件中?
  • @NadiaChibrikova 它在一个 .js 文件中,这是问题所在,在 fetch API 调用时会出现此错误。
  • 它要求您使用 unsafe-inline,这表明存在一些内联代码。你能提供一个你的代码示例吗?
  • @NadiaChirkova 添加了
  • 这个函数在后台脚本吗?从哪里调用?

标签: google-chrome-extension content-security-policy


【解决方案1】:

拒绝执行内联事件处理程序,因为...

这意味着您在标签中使用内联事件处理程序,例如:<tag onclick='some_js_code'>、<select onchange='js_funct()'、<body onload='some_handler()'> 等。
所有这些都需要script-src 中的'unsafe-inline'(目前还没有任何使用'unsafe-hashes' 和'hash-value' 令牌支持跨浏览器的解决方法)。

避免此错误且不使用'unsafe-inline' 的最佳方法是通过addEventListener() 挂起事件处理程序。

因为你确实使用了 jQuery,所以它是 very easy。

PS:您没有显示完整的 CSP,但 fetch("http://127.0.0.1:5000/create/" 在 Dev 和 Prod 中需要 connect-src 'self' http://127.0.0.1:5000 和 connect-src 'self'。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2020-01-12
    • 2018-03-30
    • 2016-04-29
    • 2017-04-01
    相关资源
    最近更新 更多