1 year ago

#76354

test-img

Abdullah Ch

How to register a FCM Push Notification Receiving Service Worker in Vue 2

I am using firebase version 8.2.7

Code in public/firebase-messaging-sw.js

//firebase-messaging-sw.js

importScripts("https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/8.2.7/firebase-messaging.js");

const firebaseConfig = {
  // firebase config credentials
};
const app = firebase.initializeApp(firebaseConfig);

const messaging = app.messaging();

messaging.onBackgroundMessage((payload) => {
  console.log("[firebase-messaging-sw.js] Received background message ", payload);
  // Customize notification here
  const notificationTitle = "Background Message Title";
  const notificationOptions = {
    body: "Background Message body.",
    icon: "/firebase-logo.png"
  };

  self.registration.showNotification(notificationTitle,
    notificationOptions);
});

Code in firebase.js


//firebase.js

import firebase from "firebase/app";
import "firebase/firebase-messaging";

const firebaseConfig = {
  // firebase config credentials
};  

firebase.initializeApp(firebaseConfig);

export default firebase.messaging();

Code in main.js


import firebaseMessaging  from "./firebase"; // firebase

firebaseMessaging.getToken({ 
  vapidKey: process.env.VUE_FIREBASE_PUSH_KEY })
  .then((currentToken) => {
    if (currentToken) {
      console.log("Firebase Current Token", currentToken);
      // this.$messaging.onMessage((msg) => {
      //   window.alert(msg);
      // });
      // // getMessaging(payload => {
      // //   console.log("//////////////message Firebase", payload);
      // //   window.alert(payload);
      // // });
    } else {
      console.log("No registration token available. Request permission to generate one.");
    }}).catch( err => {
    console.log("/////////errrr Firebase", err);
  });         

Vue.prototype.$messaging = firebaseMessaging;



new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");

randomComponent.js


methods: {
  getFirebaseNotifications() {
       try {
        this.$messaging.onMessage((payload) => {
          console.log("//////////////message Firebase", payload);
        });
      } catch (error) {
        console.log("/////////errrr Firebase", error);
      }
     
    },
}

 created() {
     this.getFirebaseNotifications();

  }

What changes should I make in public/firebase-messaging-sw.js to receive the push notifications from Firebase Cloud Messaging (FCM) whenever they are created and how can I register such a service worker in my vue app. Also, how can I receive the FCM notifications in my vue components ?

firebase

vue.js

vuejs2

firebase-cloud-messaging

service-worker

0 Answers

Your Answer

Accepted video resources