1

I would like to use JavaScript tags inside HTML files in Electron.

I know I can use code like this in main.js:

webPreferences: { preload: path.join(__dirname, "preload.js"), },

And then import this script in HTML files like this:

<script>alert("This works!")</script>

But why can't I just use JavaScript like this inside HTML files:

alert("Why won't this work?");

There is a default meta tag in HTML when I follow Electron's quick start guide: <meta http-equiv="X-Content-Security-Policy" content="default-src 'self'; script-src 'self'" />

And this I guess disables executing inline JavaScript.

So my question is, is it bad practice to use inline JavaScript like this in Electron? Should this be avoided?

3
  • "But why can't I just use JavaScript like this inside HTML files:" Do you mean without using <script></script> tags? Commented Apr 1, 2022 at 12:40
  • "And this I guess disables executing inline JavaScript." That's not correct. Your meta tag only disallows external script sources. If you are not able to use <script> tags, then there is probably a script that is parsing your code. Commented Apr 1, 2022 at 13:02
  • @RezaSaadati I thought that 'unsafe-inline' was required in the CSP to allow <script></script>. developer.mozilla.org/en-US/docs/Web/HTTP/Headers/… Commented Apr 1, 2022 at 13:06

1 Answer 1

1

yes you can use javascript inside HTML files by using the script tag .

<script>
     //code goes here
</script>

now coming to use of inline javascript its not a good practice if you are creating a project because then it will be hard to maintain if you start working with multiple files.

Sign up to request clarification or add additional context in comments.

3 Comments

Should this inline JavaScript be avoided in Electron?
Best practice is to use separate files for your JavaScript but, as with most things, the decision is up to you.
Exactly as @phuzi mentioned its better to have separate JS files but if you are say using only one HTML file and want to add just a little bit of javascript its fine to use the script tag

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.