简体   繁体   中英

Service Worker PostMessage Error

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?

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM