最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Service Worker PostMessage Error - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 6

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');
发布评论

评论列表(0)

  1. 暂无评论