1
votes

I have been working on service worker since last 15 days. Its pretty fast to learn but since then I am stuck on this notification support on my website.

The problem I am facing is notification is not shown even though its received in push event registered with service worker.

But it gets shown when some other desktop notification is received via services like pushcrew.com and you click see it in action then my notification gets displayed.

   <!DOCTYPE html>
    <html>
    <head>
      <title></title>
      <link rel="manifest" href="./manifest.json">
   </head>
   <body>

<script type="text/javascript">
    window.onload = function(){
//    console.debug("Onload");

        navigator.serviceWorker
            .register('./service-worker.js')
            .then(function(registration){
                console.log("registration");

                registration.onupdatefound = function() {
                    var installingWorker = registration.installing;

                    installingWorker.onstatechange = function() {
                        switch (installingWorker.state) {
                            case 'installed':
                                if (navigator.serviceWorker.controller) {
                                    // At this point, the old content will have been purged and the fresh content will
                                    // have been added to the cache.
                                    // It's the perfect time to display a "New content is available; please refresh."
                                    // message in the page's interface.
                                    location.reload(true);
                                }
                                else {
                                    // At this point, everything has been precached.
                                    // It's the perfect time to display a "Content is cached for offline use." message.
                                }

                                break;
                            case 'redundant':
                                console.error('The installing service worker became redundant.');
                                break;
                            case 'activating':
                                console.log("activating");
                                break;
                            case 'activated':
                                registration.pushManager.subscribe({
                                    userVisibleOnly: true
                                }).then(function(sub) {
                                    console.log('endpoint:', sub.endpoint);
                                    document.write(sub.endpoint);

                                });
                                console.log("activated");
                                break;
                            default:
                                console.log("Default Condition" + installingWorker.state);
                                break;
                        }
                    }
                };

            })
            .catch(function(err){
//              alert("Service worker registration failed ");

            });


    }
</script>
</body>
</html>

Manifest.json

  {
"name": "WorkIndia",
"short_name": "WorkIndia",
"icons": [{
  "src": "icon-128x128.png",
    "sizes": "128x128",
    "type": "image/png"
  }, {
    "src": "icon-144x144.png",
    "sizes": "144x144",
    "type": "image/png"
  }, {
    "src": "icon-152x152.png",
    "sizes": "152x152",
    "type": "image/png"
  }, {
    "src": "icon-192x192.png",
    "sizes": "192x192",
    "type": "image/png"
  }, {
    "src": "icon-256x256.png",
    "sizes": "256x256",
    "type": "image/png"
  }],
"permissions": [
    "notifications"
  ],
"web_accessible_resources": [
  "icon-128x128.png"
],
"start_url": "index.html",
"display": "standalone",
"background_color": "#3E4EB8",
"theme_color": "#2F3BA2",
"gcm_sender_id": "234031710894"

}

service-worker.js

  'use strict';

  self.addEventListener('push', function(event) {
  //  if (self.skipWaiting) { self.skipWaiting(); }

  var notificationTitle = 'Hello';
  var notificationOptions = {
      body: 'Thanks for sending this push msg.',
      tag: 'simple-push-demo-notification',
      data: {
        url: 'https://developers.google.com/web/fundamentals/getting-started/push-notifications/'
      }
  };
  if (event.data) {
      const dataText = event.data.text();
      notificationTitle = 'Received Payload';
      notificationOptions.body = "Push data: " + dataText;
  }

  console.debug('Received a push message', event);

 event.waitUntil(
     self.registration.showNotification(notificationTitle, notificationOptions)
 );
});

self.addEventListener('notificationclick', function(event) {
console.log('On notification click: ', event.notification.tag);
// Android doesn’t close the notification when you click on it
// See: http://crbug.com/463146
event.notification.close();

// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(clients.matchAll({
  type: 'window'
}).then(function(clientList) {
  for (var i = 0; i < clientList.length; i++) {
    var client = clientList[i];
    if (client.url === '/' && 'focus' in client) {
      return client.focus();
    }
  }
  if (clients.openWindow) {
    return clients.openWindow('/');
  }
}));
});

Console

(index):16 registration
(index):41 activating
(index):51 activated
(index):47 endpoint: https://android.googleapis.com/gcm/send/coiKeSkPta0:APA91bGUTJD6TciT1HANKGd…HqUEz5iQY7y9I_BVbDbPWIv0r7zfHyhlwFl91odzSIhr71IPXDK4ie6ok3yWTN-pflj16Vezq5
service-worker.js:20 Received a push message PushEvent {data: null, type: "push", target: ServiceWorkerGlobalScope, currentTarget: ServiceWorkerGlobalScope, eventPhase: 2…}bubbles: falsecancelBubble: falsecancelable: falsecomposed: falsecurrentTarget: ServiceWorkerGlobalScopedata: nulldefaultPrevented: falseeventPhase: 0path: Array[0]returnValue: truesrcElement: ServiceWorkerGlobalScopetarget: ServiceWorkerGlobalScopetimeStamp: 0type: "push"__proto__: PushEvent
1

1 Answers

1
votes

You have permission for the notifications, but not for using gcm. This may be the reason for the issue you're having.

You'll have to add gcm in the permissions list (as indicated in the GCM Documentation).

"permissions": [
    "gcm", ... // Other permissions, like "storage"
]

Also, since the event function is already a callback, I don't see the need to have to use waitUntil to showNotification. Just call the function after the console.debug, it may help with the issue as well.