与 Web Worker 进行通信

由于工作人员在创建它们的单独线程中运行,因此需要通过 postMessage 进行通信。

注意: 由于导出前缀不同,有些浏览器有 webkitPostMessage 而不是 postMessage。你应该覆盖 postMessage,以确保工人在大多数地方工作(没有双关语):

worker.postMessage = (worker.webkitPostMessage || worker.postMessage);

从主线程(父窗口):

// Create a worker
var webworker = new Worker("./path/to/webworker.js");

// Send information to worker
webworker.postMessage("Sample message");

// Listen for messages from the worker
webworker.addEventListener("message", function(event) {
    // `event.data` contains the value or object sent from the worker
    console.log("Message from worker:", event.data); // ["foo", "bar", "baz"]
});

来自工人,在 webworker.js

// Send information to the main thread (parent window)
self.postMessage(["foo", "bar", "baz"]);

// Listen for messages from the main thread
self.addEventListener("message", function(event) {
    // `event.data` contains the value or object sent from main
    console.log("Message from parent:", event.data); // "Sample message"
});

或者,你也可以使用 onmessage 添加事件监听器:

从主线程(父窗口):

webworker.onmessage = function(event) {
    console.log("Message from worker:", event.data); // ["foo", "bar", "baz"]
}

来自工人,在 webworker.js

self.onmessage = function(event) {
    console.log("Message from parent:", event.data); // "Sample message"
}