The Problem:
You wish to use eval()
in your Chrome Extension code, but you’re encountering an unsafe-eval
error. Despite having granted the unsafe-eval
permission in your CSP Manifest, the error persists. You’re using Webpack to compile your code, which relies on eval()
for source map generation.
The Solutions:
Solution 1: WebExtensions Content Security Policy
Chrome extensions are subject to strict Content Security Policies (CSP), which disallow the use of ‘unsafe-eval’ and ‘eval’ for security reasons. Webpack, commonly used for compiling Chrome extensions, utilizes ‘eval’ for generating source maps, leading to the ‘unsafe-eval’ error.
To resolve this issue, it’s crucial to understand the CSP limitations for WebExtensions and adhere to these restrictions. Inline scripts with content like
alert('hello')
are not permissible. Instead, you’ll need to calculate the SHA256 value of the script’s contents and add it to your manifest as an allowed script.
Solution 3: Relaxing CSP
To resolve the “unsafe-eval” error in Webpack-compiled Chrome extensions, you can relax your Content Security Policy (CSP) by adding the ‘unsafe-eval’ directive. Update your manifest.json file under the “content_security_policy” property as follows:
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
Caution: While this solution allows ‘eval()’ usage, it is strongly discouraged due to its vulnerability to XSS attacks. Consider alternative approaches to handle source maps or explore browser-specific CSP overrides.
Solution 4: Use Less Verbose Source Maps
For Vue CLI-generated projects, there’s no webWebpack.config.js
. Instead, add the following configuration to vue.config.js
:
Webpack: {
devtools: 'cheap-module-source-map',
}
Solution 5: Disable Source Maps
To quickly resolve the issue, use the `–no-devtool` flag with the Webpack CLI command:
npx webpack watch --no-devtool
This will prevent Webpack from generating source maps, which require `eval()` code and will prevent the “unsafe-eval” error.
Q&A
How can I permit the use of eval() in my code (because Webpack uses this to generate source maps)?
unsafe-eval
, or eval
at all in fact.
How to fix unsafe-eval
error in Chrome extension compiled by Webpack?
devtool: 'cheap-module-source-map'
Is there a workaround for this unsafe-eval
restriction?
webpack.config.js
, so the solution will be adding the following config into vue.config.js
: configureWebpack: { devtool: 'cheap-module-source-map' }