Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Service worker onload show notifications

I have a service worker that is registered, but I want to loop a function to check for updates on the server and show a notification even when tabs are closed.

With the following code in the serviceworker.js, I get an error; "Uncaught (in promise) TypeError: No active registration available on the ServiceWorkerRegistration."

self.registration.showNotification(title, {
        body: 'We have received a push message',
        icon: '',
        tag: ''
})

I want the notification to pop up when the browser is opens like how Facebook does it.

like image 262
Relm Avatar asked Nov 09 '22 20:11

Relm


1 Answers

Well, you need to understand first the lifecyle of service-worker

    // listen for a push notification from gcm, as only it can reiterate 
    // your push-notifications to your clients subscriber id
    // put your code inside listener

       self.addEventListener('push', function(event) {  
          console.log('Received a push message', event);

         // here you can make rest calls to fetch data against the subscriber-id 
         // and accordingly, set data 
         // keep in mind that your server sends push notifications to gcm
         // and then your subscribers receive them here

         var title = 'title' || 'data-from-rest-call';  
         var body = 'body' || 'data-from-rest-call';  
         var icon = '/your image path' || 'data-from-rest-call';  
         var tag = 'tag' || 'data-from-rest-call';

         // waitUntil is a callback, it triggers when the push is ready.
         event.waitUntil(  
         //here your ready notifications get triggered
         self.registration.showNotification(title, {  
           body: body,  
           icon: icon,  
           tag: tag  
         })  
      );  
    });

Refer google's getting started with web-push-notifications for detailed understanding.

like image 151
anshulix Avatar answered Nov 15 '22 07:11

anshulix