From this answer, I know that a parent process can talk to a child worker, but how about the other way around?
Asked
Active
Viewed 889 times
1 Answers
4
From the worker you have to use Worker.postMessage
self.postMessage('hi')
And in the main process:
const worker = new Worker("./worker.js", { type: "module", deno: true });
worker.addEventListener('message', message => {
console.log('message', message);
// message.data === 'hi'
});
Regarding self
The Window.self read-only property returns the window itself, as a WindowProxy. It can be used with dot notation on a window object (that is, window.self) or standalone (self). The advantage of the standalone notation is that a similar notation exists for non-window contexts, such as in Web Workers. By using self, you can refer to the global scope in a way that will work not only in a window context (self will resolve to window.self) but also in a worker context (self will then resolve to WorkerGlobalScope.self).

Marcos Casagrande
- 37,983
- 8
- 84
- 98
-
Where comes the self variable? – Wong Jia Hau May 30 '20 at 06:25
-
1From the worker, it's in the worker scope. You can see it in the link. – Marcos Casagrande May 30 '20 at 09:03
-
well it's a global object, in the browser you can do: `self === window`. In the worker `self` is the worker. – Marcos Casagrande May 30 '20 at 11:10
-
1Thanks I found the reference here https://developer.mozilla.org/en-US/docs/Web/API/Window/self – Wong Jia Hau May 30 '20 at 12:46