Skip to main content

Messaging Worker

To setup messaging service, you need to add a messaging worker on your site at your public directory. You can do that by creating a messaging-init-sw.js file in the public directory and add the following code.

public/messaging-init-sw.js

/* eslint-disable no-undef */
// 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/10.5.2/firebase-app-compat.js'
);
importScripts(
'https://www.gstatic.com/firebasejs/10.5.2/firebase-messaging-compat.js'
);

/** @typedef {{
* uri: string;
* name: string;
* type: string;
* }} Attachment */

/** @typedef {{
* message: string;
* attachments: Attachment[];
* custom: string;
* type: string;
* }} MessageBody */

try {
const url = new URL(location);
/** @type {import('firebase/app').FirebaseOptions} */
const config = JSON.parse(url.searchParams.get('config'));

/** @type {import('firebase/app').FirebaseApp} */
const app = firebase.initializeApp(config, config.appId);
/** @type {import('firebase/messaging').Messaging} */
const messaging = firebase.messaging(app);

// Modify in here to handle the notification on background
messaging.onBackgroundMessage(
/** @type {import('firebase/messaging').MessagePayload} */
async (message) => {
if (!message.data || !message.data['busy-hour']) return;

/** @type {MessageBody} */
const payload = JSON.parse(message.data['busy-hour'] || '{}');

// Show the notification using the payload with the showNotification functions
// self.registration.showNotification
}
);
} catch (err) {
console.warn('No config found.');
}