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));
}
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));
});
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',
})
})
You may have chrome notifications blocked. A good hint this is the case is if you aren't being constantly spammed with notifications from other websites. This answer worked for me.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.