在PWA上,我正在尝试在活动页面和服务工作者之间建立通信。我开始编写以下代码:
// webpage
window.addEventListener("message", function (event) {
console.log(event);
});
$(document).ready(function() {
console.log("APP - Document ready");
navigator.serviceWorker.getRegistration('/')
.then((registration) => {
if (registration.active) {
console.log('APP - WEB ===> SW');
registration.active.postMessage('WEB ===> SW');
}
});
// ...
}
// service worker
self.addEventListener('message', function (event) {
console.log("SW - " + event.source);
console.log("SW - SW ===> WEB");
event.source.postMessage("SW ===> WEB");
});
给出的输出:
APP - Document ready
APP - WEB ===> SW
SW - [object WindowClient]
SW - SW ===> WEB
在浏览器的Web控制台中使用window.postMessage("test");
成功触发了应用程序的消息处理程序,并且服务人员的postMessage
调用没有收到任何错误,所以我不知道我在这里做错了什么: -/