與 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"
}