Mubashir
Mubashir

Reputation: 4204

Google Chrome Push Notification

I am implementing chrome push notification for my website users. Which I am able to do successfully. I have two question ?

1) how to get the previous subscription id whenever i block the notification from browser setting. I have to remove the subscription id from my backend server

2) whenever i reload the website pushManager.subscribe method is running every time in which i am sending subscription id to server due to which the API is hitting every time with same subscription id

push.js

'use strict';

if ('serviceWorker' in navigator) {
  console.log('Service Worker is supported');
  navigator.serviceWorker.register('service_worker.js').then(function() {
    return navigator.serviceWorker.ready;
  }).then(function(reg) {
    console.log('Service Worker is ready :^)', reg);
    reg.pushManager.subscribe({userVisibleOnly: true}).then(function(sub) {
      console.log('endpoint:',JSON.stringify(sub.endpoint));
       console.log(sub.endpoint.substring('https://android.googleapis.com/gcm/send/'.length));
    });
  }).catch(function(error) {
    console.log('Service Worker error :^(', error);
  });
}

service-worker.js

'use strict';
var myurl;
console.log('Started', self);

self.addEventListener('install', function(event) {
  self.skipWaiting();
  console.log('Installed', event);
});

self.addEventListener('activate', function(event) {
  console.log('Activated', event);
});


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

      event.waitUntil(  
      fetch('/notify.json').then(function(response) { 
            return response.json().then(function(data) { 
            console.log(JSON.stringify(data));
                var title = data.title;  
                var body = data.body;  
                myurl=data.myurl;     

                return self.registration.showNotification(title, {  
                  body: body,  
                  icon: 'profile.png',  
                  tag: 'notificationTag'  
                }); 

            });  
      }).catch(function(err) {  
          console.error('Unable to retrieve data', err);

          var title = 'An error occurred';
          var body = 'We were unable to get the information for this push message';  

          return self.registration.showNotification(title, {  
              body: body,  
              icon: 'profile.png',  
              tag: 'notificationTag'  
            });  
        })  
      );   
});

  // var title = 'Vcona';
  // event.waitUntil(
  //   self.registration.showNotification(title, {
  //     'body': 'School Management',
  //     'icon': 'profile.png'
  //   }));



self.addEventListener('notificationclick', function(event) {
  console.log('Notification click: tag', event.notification.tag);
  // Android doesn't close the notification when you click it
  // See http://crbug.com/463146
  event.notification.close();
  var url = 'https://demo.innotical.com';
  // Check if there's already a tab open with this URL.
  // If yes: focus on the tab.
  // If no: open a tab with the URL.
  event.waitUntil(
    clients.matchAll({
      type: 'window'
    })
    .then(function(windowClients) {
      console.log('WindowClients', windowClients);
      for (var i = 0; i < windowClients.length; i++) {
        var client = windowClients[i];
        console.log('WindowClient', client);
        if (client.url === url && 'focus' in client) {
          return client.focus();
        }
      }
      if (clients.openWindow) {
        return clients.openWindow(myurl);
      }
    })
  );
});

Upvotes: 0

Views: 2229

Answers (2)

Matt Gaunt
Matt Gaunt

Reputation: 9821

Best pieces of advice I can give:

  1. Keep track of your subscription (especially what you send to your server) in indexDB. Why IndexDB?
    1. You can update indexDB in the window and in the serviceworker. This is important as you'll first get a PushSubscription in the window, but serviceworker will dispatch pushsubscriptionchange events which you should listen for and attempt to get a new PushSubscription, if you can.
  2. When the page loads, check indexDB for an old subscription, if it exists, compare it to getSubscription() (i.e. your current subscription). This check should include any values you need server side, for example, when browsers go from not supporting payloads, to supporting them, they go from having no keys, to suddenly having keys - so you should check if you server has these keys or not.
  3. DO NOT USE any of the API's for GCM, this will NOT work on other browsers (Firefox, Opera, Samsung Browser + others in the future) and aren't needed.

Upvotes: 1

Danylo Gudz
Danylo Gudz

Reputation: 2646

1) You can't get previous reg id. There are to ways:

  1. Every time you subscribe for notifications you can save it to a local chrome db(for example indexdb) and when you subscribe another time you just restore you previous reg id from this db.
  2. When you send a notification to GCM it responds you with canonical ids and another information about correctness of reg ids, so you can remove invalid one

2) You have to check first if subscription id already exists, then subscribe if not:

if ('serviceWorker' in navigator) {
  console.log('Service Worker is supported');
  navigator.serviceWorker.register('service_worker.js').then(function() {
    return navigator.serviceWorker.ready;
  }).then(function(reg) {
    console.log('Service Worker is ready :^)', reg);
    reg.pushManager.getSubscription().then(function(subscription) {
        if(!subscription) {
            reg.pushManager.subscribe({userVisibleOnly: true}).then(function(sub) {
                console.log('endpoint:',JSON.stringify(sub.endpoint));
                console.log(sub.endpoint.substring('https://android.googleapis.com/gcm/send    /'.length));
                //send new subscription id to server
                return;
            });
        }
    });

  }).catch(function(error) {
    console.log('Service Worker error :^(', error);
  });
}

Upvotes: 0

Related Questions