1

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.

FluffyBike
  • 825
  • 1
  • 4
  • 17
  • Show your server-side code. – SuperStormer Jun 24 '22 at 07:37
  • Instead of trying to fix inline javascript, why not create a script file a link that instead? – Reyno Jun 24 '22 at 07:42
  • @SuperStormer, I'm using this quick start guide for electron: https://www.electronjs.org/docs/latest/tutorial/quick-start/ So I don't really have any server side code. – FluffyBike Jun 24 '22 at 07:46
  • @Reyno, having the script in a separate file is my eventual goal. But I would like to start by simply having the script inline with the html. – FluffyBike Jun 24 '22 at 07:46

1 Answers1

2

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>
Reyno
  • 6,119
  • 18
  • 27