4
votes

currently I am developing web push notification service for our project. The problem I am facing is that my service worker in Google Chrome receives push signal, but won't show it as notification, although I am able to log data to dev console. I tried it on Firefox and also on Chrome in another devices and it does work. I tried to restore chrome settings, but it's not helping. Here is my service worker code:

'use strict';

self.addEventListener('push', function(event) {
console.log('[Service Worker] Push Received.');
console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);

var payloadJson = JSON.parse(event.data.text());

const title = payloadJson.title;
const options = {
    body: payloadJson.message,
    icon: 'img/img.png',
    badge: 'img/img2.png'
};

event.waitUntil(self.registration.showNotification(title, options));
});

After push service worker logs messages as expected: Dev tools console log

As I mentioned I tested it on chrome with another device which had Chrome v64 meanwhile mines is v65.0.3325.162 Both of devices runs on Mac OS High Sierra 10.13.3

EDIT: So i found some strange behaviour, after completely deleting chrome with all cached files and reinstalling it I was able to make it work, but now the issue is, that if I wait till notification will dissaper it will not be shown next time. Everything works until I click close on notification.

2
Have you found a fix? - Merv

2 Answers

0
votes

To send a notification, the payload must use the notification key:

var payload = {
    notification: {
        title: 'My Title',
        body : 'TEST'
    }
};

See this answer: https://stackoverflow.com/a/47379794/2292766

0
votes

I've discovered that if the options argument for the showNotification() is invalid, i.e. the file(s) specified in either the icon or image field don't exist, then the method call silently resolves without raising an error or anything. This is probably why you see the push event coming in yet not seeing the notification itself. I'm not sure about the connection with the behavior you explained after reinstalling the service worker, though.