Service Worker PostMessage Error

六眼飞鱼酱① 提交于 2020-03-21 05:41:42

问题


I have the following:

//main.js
if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('worker.js').then(function(worker){
//      firebase.messaging().useServiceWorker(worker);
    navigator.serviceWorker.controller.postMessage([MESSAGE HERE]);
    });
}

And in worker.js:

self.onmessage=function(e){
    console.log(e.data);
}

But in main.js, I get this error:

Uncaught TypeError: Cannot read property 'postMessage' of null

Why is this happening?


回答1:


This is because you are going into a new function with the line

navigator.serviceWorker.register('worker.js').then(function(worker){

and passing in your service worker as 'worker'

you should be able to replace

    navigator.serviceWorker.controller.postMessage([MESSAGE HERE]);

with

 worker.active.postMessage('your message');


来源:https://stackoverflow.com/questions/51291483/service-worker-postmessage-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!