Introduction

Integrating Firebase Cloud Messaging (FCM) with your Vue.js application enhances its capabilities by enabling real-time push notifications. This guide will walk you through the process of setting up FCM using CDN scripts, tailored specifically for applications configured with Webpack and .NET Core 2.2.

Step 1: Add CDN Scripts

Begin by including the necessary Firebase CDN scripts in your HTML file. These scripts are crucial for initializing and utilizing Firebase services in your project.

<!-- Add Firebase CDN Scripts -->
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.1/firebase-analytics.js"></script>

Step 2: Configure Firebase

After adding the CDN scripts to your HTML, append the following Firebase configuration at the end of the body tag:

// Initialize Firebase
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  databaseURL: "YOUR_DATABASE_URL",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID",
  measurementId: "YOUR_MEASUREMENT_ID",
}

firebase.initializeApp(firebaseConfig)
firebase.analytics()

// Initialize Firebase Messaging
const messaging = firebase.messaging()

// Request Permission for Notifications
messaging
  .requestPermission()
  .then(function () {
    console.log("Notification permission granted.")
    return messaging.getToken()
  })
  .then((token) => {
    console.log("Token:", token)
  })
  .catch((err) => {
    console.error("Unable to get permission to notify.", err)
  })

// Handle incoming messages
messaging.onMessage((payload) => {
  console.log("Message received. ", payload)
  localStorage.setItem(
    payload.collapse_key,
    JSON.stringify(payload.notification)
  )
})

Step 3: Add Firebase Service Worker

To handle notifications when your web app is in the background, include a service worker in the root directory of your project:

// Firebase Service Worker
importScripts("https://www.gstatic.com/firebasejs/7.14.1/firebase-app.js")
importScripts("https://www.gstatic.com/firebasejs/7.14.1/firebase-messaging.js")

firebase.initializeApp(firebaseConfig)

const messaging = firebase.messaging()

// Handle background messages
messaging.setBackgroundMessageHandler((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",
  }

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

Step 4: Update manifest.json

Ensure that the Firebase Cloud Messaging sender ID is included in your project’s manifest.json file:

{
  "gcm_sender_id": "YOUR_GCM_SENDER_ID"
}

Step 5: Use Local Storage to Save Notifications

Finally, leverage local storage to keep track of notifications:

// Retrieve notifications
let notification = localStorage.getItem("notification_key")
// Optionally, set an expiration for stored data

By following these steps, you can successfully configure Firebase Cloud Messaging for your Vue.js application, enabling robust push notification features that enhance user engagement and communication.