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

前端 未结 2 770
无人共我
无人共我 2020-12-15 14:30

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)

相关标签:
2条回答
  • 2020-12-15 15:19
    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! 
    
    0 讨论(0)
  • 2020-12-15 15: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'})));
    
    0 讨论(0)
提交回复
热议问题