Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play a sound with Firebase when browser receives a notification while running 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 enter image description here 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.

like image 625
Hashikami Avatar asked Nov 18 '22 06:11

Hashikami


1 Answers

While 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'
});
like image 190
Jeff Posnick Avatar answered Dec 14 '22 23:12

Jeff Posnick