Search code examples
javascripthtmlunsafe-inline

How to add 'unsafe-inline' keyword to run inline javascript?


I'm learning javascript and trying to run some inline javascript code. I'm using the electron quick start guide and the code works fine before I try to add some inline javascript. Here's my index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
    <title>Hello World!</title>
  </head>
  <body>
    <script>
      console.log("Hello World"); // <-- this is the line causing problems
    </script>
    <h1>Hello World!</h1>
    We are using Node.js <span id="node-version"></span>,
    Chromium <span id="chrome-version"></span>,
    and Electron <span id="electron-version"></span>.
  </body>
</html>

When I try to load the webpage with the console.log("Hello World") added, I get the error:

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

The error message tells me that I can add an 'unsafe-inline keyword. Exactly how do I do that?

I have tried searching for examples, like this example on SO, or this guide on content-security-policy.com. But all the examples just tells me to add 'unsafe-inline' to the content security policy, without actually showing how that's done.


Solution

  • You can add unsafe-inline by changing your meta tag to the following. However I'd suggest keeping it the same and just load JS via a separate file since changing the tag adds some security risks. It's called unsafe for a reason.

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
        <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'">
        <title>Hello World!</title>
      </head>
      <body>
        <script>
          console.log("Hello World"); // <-- this is the line causing problems
        </script>
        <h1>Hello World!</h1>
        We are using Node.js <span id="node-version"></span>,
        Chromium <span id="chrome-version"></span>,
        and Electron <span id="electron-version"></span>.
      </body>
    </html>