Reputation: 19111
I registered a service worker and am trying to test a web notification in the browser. Chrome (and Firefox) claim the service worker is successfully registered.
On load of the React App, I've granted permission to receive notifications.
In my sw.js
, I am listening for a push
event, and attempting to send a sample push message from the Chrome Application tab, as shown in the screenshot above.
self.addEventListener("push", receivePushNotification);
When clicking Push
in the Chrome Application Tab, the push
event fires, calling receivePushNotification
. However, when I attempt to show a notification in the browser, nothing happens and no error is reported.
function receivePushNotification(event) {
// This prints "Test push message from DevTools."
console.log("[Service Worker] Push Received.", event.data.text());
var options = {
body: "This notification was generated from a push!"
};
/*****
I would expect the following line to display a notification, since I've already
granted permission to allow for notifications. Yet, nothing happens and there is
no error in the console.
*****/
event.waitUntil(self.registration.showNotification("Hello world!", options));
}
Upvotes: 7
Views: 8327
Reputation: 59
This is the code that I use. It is pretty generic, and it works.
self.addEventListener('push', function (e) {
console.log('Push Received...')
const data = e.data.json()
self.registration.showNotification(data.title, {
body: 'Notified by Waelio.com!',
icon: 'https://picmymenu.s3.eu-west-3.amazonaws.com/waelio_logo.png',
})
})
Upvotes: -1
Reputation: 5941
You seem to have gone one step too far in defining your function separately / not defining it as an async function. You are also not passing the event to the function call.
What happens if you rewrite it like this?
self.addEventListener("push", function(event) {
console.log("[Service Worker] Push Received.", event.data.text());
var options = {
body: "This notification was generated from a push!"
};
event.waitUntil(self.registration.showNotification("Hello world!", options));
});
Upvotes: -1