<Permission denied> error trying to instantiate web worker object

谁都会走 提交于 2020-01-17 04:25:08

问题


Trying out the web worker API for the first time and can't seem to get a response from the background worker.

Markup:

<script src="~/Scripts/script.js"></script>
<button onclick="TriggerWorker()">Trigger Worker</button>

Contents of script.js file:

function TriggerWorker() {

    var myWorker = new Worker('worker.js');

    myWorker.onmessage = function (e) {
        console.log(e.data);
    }

    console.log(myWorker);

    myWorker.postMessage("Text sent to worker");
}

Contents of worker.js file:

onmessage = function (e) {
    postMessage('OK');
}

I can get the myWorker object to write to the console, but the response "OK" never makes it back into the console. When inspecting the myWorker object, I can see that the onmessage property is set to "Permission denied".


回答1:


The path of the file containing the worker onmessage declaration is relative to the html file - not the calling script file.

I got it working by making the following edit:

var myWorker = new Worker('../Scripts/worker.js');



回答2:


  1. The onmessage event pertains to the current window. So in script.js it should be

    self.onmessage = function (e)

instead of

myWorker.onmessage = function (e)
  1. The postMessage method pertains to the target window. So in worker.js it should be

    onmessage = function (e) { e.source.postMessage('OK'); }

instead of

onmessage = function (e) {
   postMessage('OK'); }


来源:https://stackoverflow.com/questions/28654203/permission-denied-error-trying-to-instantiate-web-worker-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!