JAVASCRIPT   120

firebase-messaging-sw.js

Guest on 3rd August 2021 11:10:48 AM

  1. // [START initialize_firebase_in_sw]
  2. // Give the service worker access to Firebase Messaging.
  3. // Note that you can only use Firebase Messaging here, other Firebase libraries
  4. // are not available in the service worker.
  5. importScripts('https://www.gstatic.com/firebasejs/5.8.2/firebase-app.js');
  6. importScripts('https://www.gstatic.com/firebasejs/5.8.2/firebase-messaging.js');
  7.  
  8. // Initialize the Firebase app in the service worker by passing in the
  9. // messagingSenderId.
  10. firebase.initializeApp({
  11.   'messagingSenderId': '{messagingSenderId}'
  12. });
  13.  
  14. // Retrieve an instance of Firebase Messaging so that it can handle background
  15. // messages.
  16. const messaging = firebase.messaging();
  17. // [END initialize_firebase_in_sw]
  18.  
  19. // If you would like to customize notifications that are received in the
  20. // background (Web app is closed or not in browser focus) then you should
  21. // implement this optional method.
  22. // [START background_handler]
  23. messaging.setBackgroundMessageHandler(function(payload) {
  24.   console.log('[firebase-messaging-sw.js] Received background message ', payload);
  25.   // Customize notification here
  26.   const notificationTitle = 'Background Message Title';
  27.   const notificationOptions = {
  28.     body: 'Background Message body.'
  29.   };
  30.  
  31.   return self.registration.showNotification(notificationTitle,
  32.       notificationOptions);
  33. });
  34. // [END background_handler]

Raw Paste


Login or Register to edit or fork this paste. It's free.