Why does not Chrome allow Web Workers to be run in

2019-01-26 00:03发布

If I try to use web workers through a JavaScript file, Chrome throws an error -

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

But it allows them if we use directly through the HTML.

The answer on Chrome can't load web worker says Chrome doesn't let you load web workers when running scripts from a local file.

Why doesn't chrome allow web workers to run locally?

Web Workers work completely fine in Firefox, Safari and in Edge

1条回答
乱世女痞
2楼-- · 2019-01-26 00:28

This question was already asked. The workers should work in HTML files opened from disk as long as you use relative path. However, if chrome implements this correctly has been disputed.

I advise that you try to use relative path in your scripts:

new Worker("./scripts/worker.js");

If that doesn't work, see this workaround: https://stackoverflow.com/a/33432215/607407

Specifically, load worker as a function, then convert the function to string:

function worker_function() {
    // all worker code here
}
var worker = new Worker(URL.createObjectURL(new Blob(["("+worker_function.toString()+")()"], {type: 'text/javascript'})));
查看更多
登录 后发表回答