Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does not Chrome allow Web Workers to be run in JavaScript?

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

like image 559
Inderpartap Cheema Avatar asked Jun 09 '16 06:06

Inderpartap Cheema


People also ask

Are web workers supported in all browsers?

Worker ? Internet Explorer 10, Firefox, Chrome, Safari and Opera support Web workers.

Where should you place JavaScript code to run in the context of a web worker?

You can run whatever code you like inside the worker thread, with some exceptions. For example, you can't directly manipulate the DOM from inside a worker, or use some default methods and properties of the window object.

Which essential JavaScript features does web workers do not have access to?

Since web workers are in external files, they do not have access to the following JavaScript objects: The window object. The document object. The parent object.

Which JavaScript method is used to initiate a web worker?

You can create a web worker using the following syntax: const worker = new Worker("<worker_file>. js"); Worker is an API interface that lets you create a thread in the background.


2 Answers

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'})));
like image 145
Tomáš Zato - Reinstate Monica Avatar answered Sep 28 '22 06:09

Tomáš Zato - Reinstate Monica


var cblock=`

function workerFunc(e){

    console.info('Hello World!',e.data.msg)
    postMessage({msg:'Complete!'})
}

addEventListener('message',workerFunc)
`    
var a=new Worker(URL.createObjectURL(new Blob( [cblock], {type:'text/javascript'} )))    
a.onmessage=function(e){ console.info('My worker called!',e.data.msg) }    
a.onerror=function(e){ console.info( JSON.stringify(e,' ',2) ) }    
a.postMessage({ msg:'Chrome WebWorkers work!' }) 

// Hello World! Chrome WebWorkers work!
// My worker called! Complete! 
like image 25
AHSMASSACHUSETTS Avatar answered Sep 28 '22 05:09

AHSMASSACHUSETTS