2

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.

enter image description here

On load of the React App, I've granted permission to receive notifications.

enter image description here

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));
}
Andy Hoffman
  • 15,329
  • 3
  • 30
  • 51

1 Answers1

0

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));
});
miknik
  • 5,201
  • 1
  • 8
  • 22
  • The `event` is implicitly passed to the function reference. Notice I left a comment on the first line of my function that states how I do, indeed, receive the text being pushed from the Chrome Devtools. – Andy Hoffman Sep 21 '20 at 22:29
  • If you want to keep the service worker alive then the event.waitUntil method must be initially called within the event callback and has to be passed a promise. The browser will then keep the worker alive until the promse settles. So if you want to use a named function it needs to be async and return a value upon resolve/reject. What happens if you try my example code above? – miknik Oct 06 '20 at 20:31