Search code examples
javascriptmeta-tagscontent-security-policy

Content Security Policy (CSP) blocking my local script


I'm creating a website as a personal project and I preview the website through live preview in VSCode. I added the CSP meta tag in the header section of the html document like this:

<meta http-equiv="Content-Security-Policy" content="script-src 'self'">

I have a simple javascript file in the same directory as the html document, which runs a script that changes some css-style on my website. The way I understand "script-src 'self'" is that it should allow my javascript file to be loaded since both the javascript file and html file (and css) have the same origin/directory.

For some reason the script doesn't work.

I tried removing the CSP meta tag completely, and the script runs fine. So I'm certain that the problem is not due to my markup.

I tried running a debugger, and found nothing wrong.

Maybe I have completely misunderstood the meaning of 'self'. In that case I would appreciate some enlightenment.


Solution

  • When you preview your website using live preview in VSCode, the HTML file is typically loaded using the file:// protocol, which represents the local file system. The script-src 'self' directive won't allow JavaScript files to be loaded from the local file system.

    For your case, you can test the files on localhost and see if its working or not, it must work. For both cases you can use:

    <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline'">