145

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.

Progo
  • 3,452
  • 5
  • 27
  • 44
  • 2
    Are you working off the file protocol? If you are set the access flag and see if it works: http://stackoverflow.com/questions/18586921/how-to-launch-html-using-chrome-at-allow-file-access-from-files-mode – epascarello Jan 28 '14 at 14:37
  • 2
    Yes, the path for the web worker is this: `file:///E:/programming/web/project/worker.js`. The path for the main project is this: `file:///E:/programming/web/project/index.html`. – Progo Jan 28 '14 at 14:42
  • 2
    Try this: http://stackoverflow.com/questions/18586921/how-to-launch-html-using-chrome-at-allow-file-access-from-files-mode – epascarello Jan 28 '14 at 14:42

16 Answers16

123

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

Vladimir Panteleev
  • 24,651
  • 6
  • 70
  • 114
Nobel Chicken
  • 1,533
  • 1
  • 11
  • 13
  • 11
    From [this answer](http://stackoverflow.com/a/6823683/1033426), `Loading a local file, even with a relative URL, is the same as loading a file with the file: protocol.` -- and it's not cool for web pages to be able to just access your file system on a whim. – ChaseMoskal Jul 20 '14 at 22:59
  • 49
    -1 firsfox will let you do this of course, provided you're **also** using file as a origin (eg. you're viewing local file in browser). It's just chrome that is broken. – Tomáš Zato Oct 29 '15 at 16:24
  • 4
    Firefox still works (yes from file://), Chrome does not in this case. – Evil Jul 03 '16 at 02:35
  • There are numerous workarounds like setting the flag in chrome settings, using a local server instead of directly accessing html or injecting the worker. – Caleb Hillary Jan 25 '22 at 07:49
72

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'})));
user229044
  • 232,980
  • 40
  • 330
  • 338
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
  • 5
    This solution is good. why in this world nothing is perfect? Every software is agitating the users with bugs,flaws,childish-behaviors etc. Firefox is also arrogant as it refuses to support "clip-path" css property. – Ĭsααc tիε βöss Sep 22 '16 at 09:29
  • 3
    I am not a js dev and don't get the point of the script tag use here. And what is the window != self check for? Can someone please explain this loading sequence? Thx. – Sharun Apr 25 '17 at 10:17
  • Script tags will be loaded by google chrome if they are in the same directory as HTML. `window!=seld` checks whether the code is running in web worker. This makes this code portable in case you load the javascript file directly in other contexts. – Tomáš Zato Apr 25 '17 at 10:19
  • @TomášZato you mean if window != self is true, code is executing in webworker context? I was googling around and couldn't find this kind of check. – Sharun Apr 25 '17 at 10:46
  • Then google what `window` and `self` variables mean in javascript. You'll see that `window` is not defined in web workers. – Tomáš Zato Apr 25 '17 at 11:08
  • dumb question, but i'm fairly new to web workers... what goes in the 'worker_function'? thanks... – treeseal7 Oct 30 '17 at 00:17
  • 2
    @treeseal7 The code that should execute in web worker context. – Tomáš Zato Oct 30 '17 at 00:25
  • 4
    I should note that you can't use importScript from a worker written like this. At least, not without an additional workaround. So you'll need more tampering for a multi-file worker. – SlugFiller Apr 18 '18 at 04:20
  • how do u debug this code, if it is converted by blob? – Momo Apr 03 '19 at 08:55
  • @TomášZato thanks for this workaround, but how do you pass arguments to the worker? Before is use `BackgroundWorker.postMessage(xArgs);`. The `postMessage` function is still the trigger for the worker, but the `xArgs` do not get passed. Is there a aprouch to pass arguments to worker with this workaround? My `console.log` looks like `Blob {size: 1420, type: "text/javascript"} WorkerMain.js:17`, `blob:null/94d14ccf-19a8-4322-aff9-9519ab9359d8 WorkerMain.js:21`, `{array: Array(16)}` (the argument which should passed) `blob:null/94d14ccf-19a8-4322-aff9-9519ab9359d8:3 WORKER START undefined` – Mar Tin Sep 05 '19 at 05:05
  • @MarTin You're probably doing something wrong. You should ask a separate question about not being able to `postMessage` – Tomáš Zato Sep 05 '19 at 09:05
  • 2
    I also noticed that, but **stringify** the variable to pass (json) `var json = JSON.stringify(xJsonArgs);` and than pass like `new Worker(URL.createObjectURL(new Blob([`(${xFunction.toString()})(${json})`], { type: 'text/javascript' })));` works for me. Thanks for your response. – Mar Tin Sep 05 '19 at 09:11
  • I get this error ERROR DOMException: Failed to construct 'Worker': Access to the script at 'blob:*****' is denied by the document's Content Security Policy. – Stoyan Georgiev Jul 07 '22 at 07:49
55

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.

Robert Parcus
  • 1,029
  • 13
  • 19
37

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

Community
  • 1
  • 1
Mickaël
  • 940
  • 11
  • 9
  • On windows command window navigate to: "C:\Users\NAME\AppData\Local\Google\Chrome SxS\Application", then run chrome.exe --allow-file-access-from-files, then copy your local file path e.g. c:\temp\myWeb\index.html and paste into the url of the opened browser, done. – milesma Aug 18 '16 at 00:35
  • 5
    You can also create a shortcut and pass the flag in the target path. – Stephan B Sep 22 '16 at 19:56
  • 1
    Oh, and from the linked question, remember to close all Chrome windows before launching with the flag. – Stephan B Sep 22 '16 at 19:57
  • Yep, an other option can also be to code a Chrome Extension with right permission in it's manifest : "permissions": ["file://*/*"], like in https://stackoverflow.com/questions/19493020/adding-file-permission-to-chrome-extension – Mickaël Jun 11 '17 at 09:18
  • Note: "You have to close all the windows of Chrome before opening it with `--allow-file-access-from-files` flag on." as stated on https://stackoverflow.com/a/21771754/325418 – nonopolarity Dec 30 '19 at 14:11
19

It is because of the security restrictions. You need to use http:// or https:// protocol instead of file:///.

If you have NodeJS installed, you can simply do the following. - Note that this is one of many options available

Install local-web-server

$ npm install -g local-web-server

Now you can use it in any folder that you want to access the contents through http .

$ ws

Navigate to http://localhost:8000 (default port: 8000)

Safeer Hussain
  • 1,230
  • 1
  • 15
  • 27
8

I had the same problem as your post too. The solution is that you have to run it with localhost (wamp or xamp). It will done.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Thara
  • 79
  • 1
  • 1
7

Another workaround is use Google's web server for Chrome extension. Choose your work directory and start the server, Done!

Yubo
  • 71
  • 1
  • 2
7

This is inspired by Thomas answer above. But with one caveat that I wanted to distribute only the HTML, so i manually converted the js to dataURL. and enabling the data URL check box in it.

const myWorker = new Worker("data:application/x-javascript;base64,b25tZXNzYW...");
goutham
  • 105
  • 1
  • 4
6

Easy way to make local http server in chrome is this app:

Web Server for Chrome

https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb/related

Description:

A Web Server for Chrome, serves web pages from a local folder over the network, using HTTP. Runs offline. Web Server for Chrome is an open source (MIT) HTTP server for Chrome.

It runs anywhere that you have Chrome installed, so you can take it anywhere. It even works on ARM chromebooks.

It now has the option to listen on the local network, so other computers can access your files. Additionally, it can try and get an internet address.

Many people use this to do basic web development on a chromebook. It is also handy for sharing files over a local network between computers, or even on the internet.

Once you install it, navigate to http://127.0.0.1:8887

And it is not unsecure as flag --allow-file-access-from-files

A. Denis
  • 562
  • 7
  • 15
  • This is amazing! I can now run my reactJS app with web workers from local file system. Can't be much easier! – Paintoshi Dec 24 '19 at 09:16
4

you need a web server for request from HTTP protocol Instead of local file and work correctly :)

Alireza Alallah
  • 2,486
  • 29
  • 35
3

Chrome load the file but cannot run it. Use Firefox. It's working for me.

Hocine Ben
  • 2,079
  • 2
  • 14
  • 20
  • 1
    To explain my downvote: This might be better off starting with a comment, perhaps inquiring more about their browser support requirements, rather than being submitted as the answer. It seems quite likely not an answer, given what the user has already said about cross-browser support. – Thomas Poole May 05 '17 at 02:54
  • If you've read the question carefully I'm sure that you'll not down vote the response as three before you up vote it! The user is saying that Chrome can't load the worker. No, chrome can load the worker but can't run it. The reasons why I put it as a response is first the question is asked one year ago and the second many responses are saying that Firefox is not running the worker which I can't comment all of them. I'm just explaining but you've right to down vote or up vote. – Hocine Ben May 06 '17 at 18:58
2

With Python 2.x being more widely deployed than Python 3.x, something like python -m SimpleHTTPServer 8000 is more generally applicable, and not just for Mac OS X. I found it necessary for use under Cygwin, for instance.

With that in place, this example worked like a champ.

salfter
  • 119
  • 1
  • 3
2
function worker_fun(num){
    num ++
    // console.log(num)
    postMessage(num);
    setTimeout(worker_fun.bind(null,num), 500)
}

var w

function startWorker(){
    var blob = new Blob([
        "onmessage = function(e){\
            " + worker_fun.toString() + "\
            worker_fun(e.data.num);}"
    ]);
    var blobURL = window.URL.createObjectURL(blob);
    if (typeof(Worker) != 'undefined'){
        if (typeof(w) == 'undefined'){

            w = new Worker(blobURL);
            w.onmessage = function(event){
                document.getElementById('num').innerHTML = event.data;
            } 
            w.postMessage({
               num:parseInt(document.getElementById('num').innerHTML)})
        }
    }
}


function stopWorker() { 
    w.terminate();
    w = undefined;
}

As mentioned chrome does not support it. I like to define my workers in the same file. This is a working workaround which will increase a number found in innerHTML of the element the with id=num every 500ms.

1

A probably reason is chrome doesn't let you load web workers when running scripts from a local file. And I try run the code on my firefox, can not either.

Eric Chang
  • 19
  • 2
0

To load web worker from file in a project set up with Webpack and TypeScript I used a script as Tomáš Zato suggested. However, I had to modify the worker file.

worker.ts

(() => {
    console.log("worker_function loaded");
    // @ts-ignore
    window.worker_function = () => {
        self.onmessage = ({ data: { question } }) => {
            // @ts-ignore
            self.postMessage({
                answer: 42,
            });
        };
    }
})();

index.ts

async function run() {
    console.log('run()');

    const worker = new Worker(
        // @ts-ignore
        URL.createObjectURL(new Blob(["("+worker_function.toString()+")()"], { type: 'text/javascript' }))
    );

    worker.postMessage({
        question: 'The Answer to the Ultimate Question of Life, The Universe, and Everything.',
    });
    worker.onmessage = ({ data: { answer } }) => {
        console.log(answer);
    };
}

run();

index.html

<html lang="en-us">
  <head>
    <meta charset="utf-8" />
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <title>Offscreen canvas with web worker sample project</title>
    <script async type="text/javascript" src="worker.js"></script>
    <script async type="text/javascript" src="app.js"></script>
  </head>
  <body>
    <h1>web worker sample project</h1>
  </body>
</html>

webpack.config.js (version 5)

const path = require("path");
const CopyPlugin = require("copy-webpack-plugin");

module.exports = {
  mode: "production",
  entry: {
    app: "./src/index.ts",
    worker: "/src/worker.ts"
  },
  output: {
    filename: "[name].js",
    path: path.resolve(__dirname, "build")
  },
  performance: {
    hints: false
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: "ts-loader",
        exclude: /node_modules/
      },
    ]
  },
  resolve: {
    extensions: [".js", ".ts"]
  },
  plugins: [
    new CopyPlugin({
      patterns: [
        { from: "src/index.html", to: "" }
      ]
    })
  ]
};
Michael Klishevich
  • 1,774
  • 1
  • 17
  • 17
-7

Yes, It will not work in chorome if your are loading local file. But it will work fine in firefox browser. And you have to add below code in HTML file.

<head>
    <meta charset="UTF-8" />
</head>
NatNgs
  • 874
  • 14
  • 25