I wanted to explore the process of sending server messages to PWA apps. In this blog post, I will guide you through the steps I took to set up this functionality using Vite.
Important notes. By using strategies: injectManifest' we can build our own service worker, in this case to support firebase cloud messaging. To make this app fully cached and fully offline-available, we need to use the following parameter injectManifest:{globPatterns:['**/*']}*.
To build the service worker (firebase-messaging-sw.js) we first need to have at least this code:
import { precacheAndRoute } from 'workbox-precaching'
precacheAndRoute(self.__WB_MANIFEST)
To set up this app to receive all messages while the app is in the background, we will need the following configuration. Check this link to read more about firebase cloud-messaging.
import { precacheAndRoute } from 'workbox-precaching'
precacheAndRoute(self.__WB_MANIFEST)
// Give the service worker access to Firebase Messaging.
// Note that you can only use Firebase Messaging here. Other Firebase libraries
// are not available in the service worker.
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp({
apiKey: "AIzaSyCXPh_qT_9JTEbiUzFU57-fZZbDug63RiI",
authDomain: "ddavidmelo-14dc2.firebaseapp.com",
databaseURL: "https://ddavidmelo-14dc2.firebaseio.com",
projectId: "ddavidmelo-14dc2",
storageBucket: "ddavidmelo-14dc2.appspot.com",
messagingSenderId: "211150998925",
appId: "1:211150998925:web:2098c2ff8f71989ad141c4"
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
messaging.onBackgroundMessage((payload) => {
console.log(
'[firebase-messaging-sw.js] Received background message ',
payload
);
// Customize notification here
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: '/logo.png'
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
To obtain the Firebase config object, you need to create a new web app in Firebase.
Now you are ready to build the project and serve it: