I would like to know how to play a sound with Firebase Cloud Messaging (FCM) when the web browser such as Chrome, Firefox, etc. receives a notification message while running in the background.
notification while running in the background
To receive a message while the app is in the background, in FCM, call setBackgroundMessageHandler
in the service worker firebase-messaging-sw.js
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
...
return self.registration.showNotification(notificationTitle, notificationOptions);
});
However, Audio Object window.AudioContext
can not be called in service worker. In addition, The notification property Notification.sound
is not currently supported in any browser.
I would like to know how to play a sound with FCM when the app is in the background.
I would like to know how to play a sound with Firebase Cloud Messaging (FCM) when the web browser such as Chrome, Firefox, etc. receives a notification message while running in the background.
notification while running in the background
To receive a message while the app is in the background, in FCM, call setBackgroundMessageHandler
in the service worker firebase-messaging-sw.js
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
...
return self.registration.showNotification(notificationTitle, notificationOptions);
});
However, Audio Object window.AudioContext
can not be called in service worker. In addition, The notification property Notification.sound
is not currently supported in any browser.
I would like to know how to play a sound with FCM when the app is in the background.
Share Improve this question edited Oct 17, 2017 at 7:57 smyslov 1,2751 gold badge8 silver badges30 bronze badges asked Oct 17, 2017 at 7:03 HashikamiHashikami 711 silver badge2 bronze badges 1- 1 did you find a solution? – MUHAMMED IQBAL Commented Oct 2, 2020 at 6:40
3 Answers
Reset to default 4While sounds are not currently supported, you should be able to vibrate a user's device when showing a notification from inside of a service worker. That might be sufficient to get their attention. (If you really need to...)
Here's an excerpt from a live sample:
registration.showNotification('Vibration Sample', {
body: 'Your title here.',
icon: 'path/to/icon.png',
vibrate: [200, 100, 200, 100, 200, 100, 200],
tag: 'vibration-sample'
});
You wont be able to add notification sound for background message since showNotification doesn't have sound property.
You wont be able to add function inside the event listener as well, when called from service worker as the service worker doesn't have access to window from here.
You can add vibrate to showNotification, which again is only allowed for mobile device.
You should be able to add a function inside the event listener for push in the service-worker and just have it play a sound.