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?
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?
Share Improve this question asked Jul 11, 2018 at 17:44 Kento NishiKento Nishi 5981 gold badge9 silver badges24 bronze badges 3- 1 check worker.active.postMessage – Drag13 Commented Jul 11, 2018 at 17:52
- worker.active.postMessage worked! – Kento Nishi Commented Jul 11, 2018 at 17:54
- Nice to hear, have a luck – Drag13 Commented Jul 11, 2018 at 17:55
1 Answer
Reset to default 6This 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');