Notifica push web non visualizzata

Sep 16 2020

Ho registrato un addetto all'assistenza e sto provando a testare una notifica web nel browser. Chrome (e Firefox) affermano che il service worker è stato registrato correttamente.

Al caricamento dell'app React, ho concesso l'autorizzazione a ricevere notifiche.

Nel mio sw.js, sto ascoltando un pushevento e provo a inviare un messaggio push di esempio dalla scheda Applicazione Chrome, come mostrato nello screenshot sopra.

self.addEventListener("push", receivePushNotification);

Quando si fa clic Pushnella scheda dell'applicazione Chrome, l' pushevento si attiva chiamando receivePushNotification. Tuttavia, quando provo a mostrare una notifica nel browser, non accade nulla e non viene segnalato alcun errore.

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));
}

Risposte

miknik Sep 20 2020 at 05:32

Sembra che tu sia andato troppo oltre nella definizione della tua funzione separatamente / non definendola come una funzione asincrona. Inoltre, non stai passando l'evento alla chiamata di funzione.

Cosa succede se lo riscrivi in ​​questo modo?

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));
});