Skip to content

Instantly share code, notes, and snippets.

@SoarLin
Created June 2, 2018 04:28
Show Gist options
  • Save SoarLin/46fd3dfff6c0458f073c4aa03620740b to your computer and use it in GitHub Desktop.
Save SoarLin/46fd3dfff6c0458f073c4aa03620740b to your computer and use it in GitHub Desktop.
Firebase Messaging Service Worker JS
// [START initialize_firebase_in_sw]
// Import and configure the Firebase SDK
// These scripts are made available when the app is served or deployed on Firebase Hosting
// If you do not serve/host your project using Firebase Hosting see https://firebase.google.com/docs/web/setup
importScripts('https://www.gstatic.com/firebasejs/5.0.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.0.0/firebase-messaging.js');
firebase.initializeApp({
messagingSenderId: '<YOUR_SENDER_ID>'
});
const messaging = firebase.messaging();
// [END initialize_firebase_in_sw]
// If you would like to customize notifications that are received in the
// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// [START background_handler]
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
var notification = payload.notification
var notificationTitle = notification.title;
var notificationOptions = {
body: notification.body,
icon: '/static/images/logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
// [END background_handler]
@armishsonkar
Copy link

Hi SoarLin,
I am trying to replicate your FCM notification process, using main.js, service worker file and vu-register-fcm.vue file but it gives me following error in console
Uncaught FirebaseError: Messaging: This method is available in a service worker context. (messaging/only-available-in-sw)

It directs me to line 17 of this code i.e. messaging.setBackgroundMessageHandler(function(payload)
please help

Thanks,

@SoarLin
Copy link
Author

SoarLin commented Mar 28, 2020

I am not sure what is your error was caused by.
But I have update some sample on my blog(but I write in Chinese), maybe it can help you or not
blog link

@armishsonkar
Copy link

Thank You, yes it is helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment