error trying to instantiate web worke

2019-09-03 10:05发布

问题:

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'); }