Search code examples
javascriptgoogle-chromewebpackgoogle-chrome-extension

Chrome extension compiled by Webpack throws `unsafe-eval` error


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)

My CSP grants the unsafe-eval permission.

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

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


Solution

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

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

    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>
    

    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.