Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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:

newWorker("./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'})));

Solution 2:

var cblock=`

functionworkerFunc(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! 

Post a Comment for "Why Does Not Chrome Allow Web Workers To Be Run In Javascript?"