Firebase postmessage from background to JS listener is not working

Viewed 1296

I have a web app that has chat, and I would like to activate audio that I have in my JS when I receive a message when it's in the page or background or at another window tab. So it never plays the audio, only when you are on the window.

This is what I have: firebase-messaging-sw.js

messaging.setBackgroundMessageHandler(function (payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
const title = ' - ¡Mensaje Nuevo!';
const options = {
    body: 'conductor: '+payload.data.chofer_id+' - '+payload.data.mensaje,
    icon: '/icono.png',
};

  return self.clients.matchAll().then(all => all.forEach(client => {
    client.postMessage("Responding to ");
   }));

   //return self.registration.showNotification(title, options);
 });

my js in my page (here i have my audio to be played):

if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('firebase-messaging-sw.js')
                .then(function (reg) {
                    // registration worked
                    console.log('Registration succeeded. Scope is ' + reg.scope);
                }).catch(function (error) {
                    // registration failed
                    console.log('Registration failed with ' + error);
                });
        }

        navigator.serviceWorker.addEventListener('message', function handler(event) {
            console.log('Received a message from service worker: ', event.data);
            $.playSound('Sounds/Tethys.mp3');
        });
0 Answers
Related