我想在服务人员和客户端网页之间实现有效的双向通信。
这是我的代码
function twoWayMsg() {
if (navigator.serviceWorker.controller) {
var messageChannel = new MessageChannel();
messageChannel.port1.onmessage = function(event) {
console.log("Response the SW : ", event.data.message);
}
console.log("Sendingage to the service worker");
navigator.serviceWorker.controller.postMessage({
"command": "twoWayCommunication",
"message": "Hi, SW"
}, [messageChannel.port2]);
} else {
console.log("Nove ServiceWorker");
}
}
和
self.addEventListener('message', function(event) {
var data = event.data;
if (data.command == "twoWayCommunication") {
console.log("Respondingessage from the Page: ", data.message);
event.ports[0].postMessage({
"message": "Hi, Page"
});
}
});
每次都创建 MessageChannel 对象好吗?
如果我将全局变量用于消息通道对象,那么我会收到此错误
Failed to execute 'postMessage' on 'ServiceWorker': Port at index 0 is already neutered.
Error: Failed to execute 'postMessage' on 'ServiceWorker': Port at index 0 is already neutered.