由 Webpack 编译的 Chrome 扩展抛出 \`unsafe-eval\` 错误

新手上路,请多包涵

使用 Webpack 编译后重新加载我的 Chrome 扩展程序时出现此错误:

 Uncaught EvalError: 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' blob: filesystem: chrome-extension-resource:".


at new Function (<anonymous>)
at evalExpression (compiler.js:33919)
at jitStatements (compiler.js:33937)
at JitCompiler.webpackJsonp.../../../compiler/esm5/compiler.js.JitCompiler._interpretOrJit (compiler.js:34520)
at JitCompiler.webpackJsonp.../../../compiler/esm5/compiler.js.JitCompiler._compileTemplate (compiler.js:34448)
at compiler.js:34347
at Set.forEach (<anonymous>)
at JitCompiler.webpackJsonp.../../../compiler/esm5/compiler.js.JitCompiler._compileComponents (compiler.js:34347)
at compiler.js:34217
at Object.then (compiler.js:474)

我的 CSP 授予 unsafe-eval 权限。

  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"

我如何允许在我的代码中使用 eval() (因为 Webpack 使用它来生成源映射)?

原文由 Alexander Mills 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.8k
2 个回答

事实上,Chrome 扩展程序根本不允许使用 unsafe-evaleval

https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Content_Security_Policy

在制作 Chrome 扩展程序时,请了解它受到内容安全策略的严格限制。请务必阅读并理解 WebExtensions 内容安全策略。如果你想要一个内联脚本,比如:

 <script>
    alert('hello')
</script>

您必须将脚本标签内容计算为其 SHA256 值并将其添加到您的清单中,以便允许执行它。

原文由 Simon Hyll 发布,翻译遵循 CC BY-SA 3.0 许可协议

我花了几个小时,但您可能想要做的是更改 webpack 使用的源映射样式。默认情况下,它使用 eval。

https://webpack.js.org/configuration/devtool/

我将其添加到我的 webpack.config.js 中: devtool: 'cheap-module-source-map'

诀窍是弄清楚为什么 webpack --mode development 有错误而 webpack --mode production 没有。

此外,我使用的是 React 而不是 Polymer,但我很确定这仍然适用。

原文由 Randy 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题