问题
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