javascriptcorsmanifest

Access to web manifest blocked by CORS policy


I am trying to use manifest.json in my PWA. I have created a simple index.html file in a directory. I also have a manifest.json file in the directory.

Now I linked the manifest file like so::

...
<link rel="manifest" href="manifest.json" />
...

Now when I open my index.html file, the console gives an error saying it cannot fetch the manifest file due to blockage by same origin policy. How do I fix this? It's probably because I am using File protocol to open my html. And if possible, please explain why this happens, and why can I load CSS files in the same way.


Solution

  • CORS (cross origin resource sharing) is a widely used security mechanism to only allow client-side browser applications on the same domain to access resources or APIs. Anything outside the trusted CORS policy gets rejected. In the case of local web pages, files are considered to be outside your origin. Your browser essentially considers your hard drive to be on a different domain. Otherwise, malicious scripts would be able to easily access your local files by simply guessing paths to access.

    As far as local CSS is concerned it is not considered as outside origin domain. You will get same error if you try loading css from some other domain.

    To fix loading of local files you need some kind of web server or toned down dev server where your page can be hosted. One example of dev servers that can host static files: If you have Python installed python -m SimpleHTTPServer will start a server on http://localhost:8000/ in whatever folder you start it in