Chrome can't load web worker

I am working on a project that uses a web worker.

In my head section I have this code:

var worker = new Worker("worker.js");
// More code

This works fine in Safari, but Chrome reports the following error:

Uncaught SecurityError: Failed to create a worker: script at '(path)/worker.js' cannot be accessed from origin 'null'.

Why does this work perfectly in Safari but not Chrome? How do I fix this?

Thank you.


Chrome doesn't let you load web workers when running scripts from a local file.


I use a workaround. Chrome blocks Worker but not <script>. Hence the best way to make a universal solution is this:

function worker_function() {
    // all code here
}
// This is in case of normal worker start
// "window" is not defined in web worker
// so if you load this file directly using `new Worker`
// the worker code will still execute properly
if(window!=self)
  worker_function();

You then link it as normal <script src="...". And once the function is defined, you use this abomination of a code:

new Worker(URL.createObjectURL(new Blob(["("+worker_function.toString()+")()"], {type: 'text/javascript'})));

The problem has been properly explained by Noble Chicken but I have a more general solution for it. Instead of installing wamp or xamp, with python you can navigate to the folder your project is hosted in and type: python -m http.server

Just that and you will have a running server on that folder, reachable from localhost.


You can also use the --allow-file-access-from-files flag when you launch Chrome.

Example for MacOsX :

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-file-access-from-files

More info : Web worker settings for chrome