Firebase Cloud Messaging in chrome extension Manifest V3

245 views
Skip to first unread message

Tamar Y

unread,
Aug 4, 2022, 1:05:00 PM8/4/22
to Chromium Extensions

Hi, 

I posted this question at stackoverflow as well, 
Hopefully some of you can help me out with that.

 

I try to migrate my chrome-extension from manifest version 2 to v3, and was wondering if it is possible to use FCM in chrome extension Manifest version 3.

As I could not find helpful documentation/guides on this topic, I hope this thread will also be helpful to others.

In manifest version 2 I use the following code:

firebase-messaging-sw.js:

import { initializeApp } from "firebase/app";

import { getMessaging, onBackgroundMessage } from "firebase/messaging/sw";

 

const firebaseConfig = {

     apiKey: "<api-key>",

     authDomain: "<auth-domain>",

     projectId: "<project-id>",

     storageBucket: "<storage-bucket>",

     messagingSenderId: "<messaging-sender-id>",

     appId: "<app-id>",

};

 

// Initialize Firebase

initializeApp(firebaseConfig);

 

const messaging = getMessaging();

 

onBackgroundMessage(messaging, async (payload) => {

    console.log('[firebase-messaging-sw.js] Received background message ', payload);

 

    const allClients = await self.clients.matchAll({ includeUncontrolled: true, type: 'all' })

 

    allClients.forEach((client: any) => {

        client.postMessage({ type: 'msg_type', payload });

    });

});

 

In the background.js (now my SW):

if ('serviceWorker' in navigator) {

 

    const firebaseConfig = {

        apiKey: "<api-key>",

        authDomain: "<auth-domain>",

        projectId: "<project-id>",

        storageBucket: "<storage-bucket>",

        messagingSenderId: "<messaging-sender-id>",

        appId: "<app-id>",

    };

 

    // Initialize Firebase

    const app = initializeApp(firebaseConfig);

 

    // Initialize Firebase Cloud Messaging and get a reference to the service

    const messaging = getMessaging(app);

 

    getToken(messaging, { vapidKey: "<vapid-key>" })

        .then((registrationToken: string) => {

 

            onMessage(messaging, async (payload) => {

                //doSomething

            });

 

        });

 

    navigator.serviceWorker.addEventListener('message', async (message: MessageEvent) => {

        if (message.data.type === 'msg_type') {

            //doSomething

        }

    });

 

}

I try to follow this guide, and other related threads/videos, But there is no guide for firebase-messaging-sw.js or other alternatives that I have found.

Hope you can help with this.

Reply all
Reply to author
Forward
0 new messages