Javascript web workers: why do I need to postMessa

2019-05-28 21:56发布

I am a newcomer to Javascript and web programming in general. I am trying to figure out web workers, and have the following code (running in chrome):

worker_example.html

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="worker_example.js"></script>
    </head>
<html>

worker_example.js

var worker = new Worker("worker.js");

worker.addEventListener('message', function(e) {
    document.write("hello");
}, false);

worker.postMessage("");

worker.js

// self.postMessage("");

My question is why doesn't worker.postMessage("") trigger the event? If I uncomment the single line in worker.js, however, everything works fine.

1条回答
Emotional °昔
2楼-- · 2019-05-28 22:45

The event listener attached to worker listens for messages coming from the worker to the parent page. You need to register a listener in the worker as well.

parent.js

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

worker.addEventListener('message', function (e) {
  console.log(e.data);
});

worker.postMessage('marco');

worker.js

self.addEventListener('message', function (e) {
  self.postMessage(e.data + ' polo');
});
查看更多
登录 后发表回答