本文介绍了Webpack 编译的 Chrome 扩展抛出 `unsafe-eval` 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I get this error when reloading my Chrome Extension after compiling using Webpack:

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 权限.

My CSP grants the unsafe-eval permission.

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

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

How can I permit the use of eval() in my code (because Webpack uses this to generate source maps)?

推荐答案

chrome 扩展实际上不允许使用 unsafe-evaleval.

A chrome extension is not allowed to use unsafe-eval, or eval at all in fact.

https://developer.mozilla.org/en-US/加载项/WebExtensions/Content_Security_Policy

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

When making a Chrome extension understand that it's severely limited by Content Security Policies. Make sure you read and understand the WebExtensions Content Security Policy. If you want to have an inline script like:

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

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

You're gonna have to calculate the script tags contents into its SHA256 value and add that to your manifest in order for it to be allowed to be executed.

这篇关于Webpack 编译的 Chrome 扩展抛出 `unsafe-eval` 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 17:09