M
M
midia212021-10-12 08:05:54
JavaScript
midia21, 2021-10-12 08:05:54

How to play a sound on the site when a push notification is received, on an inactive tab?

firebase has an onMessage method that registers a function that fires when a new push is received.

let messaging = firebase.messaging();

messaging.onMessage(function (payload) {
            console.log("Message received. ", payload);

            let notificationSound = new Audio("/assets/audio/notification.wav");
            notificationSound.play();
});


In this function, I register a new audio file (notification sound) and play it. Everything works fine when the page to which the push comes is active in the browser. However, the sound is not played if the page is inactive (the tab is open but not in focus). I think this is due to the policy of browsers (I'm testing on Chrome). Are there workarounds? Thanks in advance.

PS Here https:
//stackoverflow.com/questions/33196475/playi ...
suggested to take out the loading of the audio file outside the handler so that it is loaded in advance, but this did not help either.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
midia21, 2021-10-12
@midia21

Found the problem. Turns out onMessage is only called when the tab is active. For background tabs, you need to use setBackgroundMessageHandler. But this method has no connection to the DOM and therefore will not be able to directly launch the audio. To solve the problem, you can send an event to the client from the service worker via postMessage, and receive it via

navigator.serviceWorker.addEventListener("message", function (event) {
        notificationSound.play();
});

running "ding"

S
Sergey Sokolov, 2021-10-12
@sergiks

Try downloading the audio file beforehand. By event, already play it:

const notificationSound = new Audio("/assets/audio/notification.wav")
let messaging = firebase.messaging();

messaging.onMessage(function (payload) {
            console.log("Message received. ", payload);
            notificationSound.play();
});

Background tabs have limited resources : timers fire less often, page rendering.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question