Answer the question
In order to leave comments, you need to log in
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();
});
Answer the question
In order to leave comments, you need to log in
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();
});
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();
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question