简体   繁体   中英

Can I run Firebase Cloud Messaging entirely in a web service worker?

TLDR: Is it a problem if you don't have FCM code running in the foreground of the application? Are there any problems that may arise from having everything in a web worker?


I have the following service worker:

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

firebase.initializeApp({ ... });

const messaging = firebase.messaging();

self.addEventListener('activate', event => {
    console.log('Service worker activating...');

    // Add the public key generated from the console here.
    messaging.usePublicVapidKey();

    // Get Instance ID token. Initially this makes a network call, once retrieved
    // subsequent calls to getToken will return from cache.
    messaging.getToken().then((currentToken) => {
        console.log("currentToken", currentToken);

        if (currentToken) {
            // sendTokenToServer(currentToken);
        } else {
            console.error('No Instance ID token available. Request permission to generate one.');
        }
    }).catch((err) => {
        console.error('An error occurred while retrieving token. ', err);
    });

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

If this service worker is started like so:

if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker.register('js/service-worker.js')
        .then(registration => {
            console.log('Service Worker is registered', registration);
        })
        .catch(err => {
            console.error('Registration failed:', err);
        });
    });
}

Is it a problem if the onTokenRefresh callback is never handled, given that this can only be handled in the foreground.

Does this setup of FCM seem correct?

Do you want to use specify an existing service worker have named js/service-worker.js ?

The Firebase messaging default service worker file name is firebase-messaging-sw.js .

If you want to use specify an existing service worker then you should specify an existing service worker with useServiceWorker.

See:

your app must define the Firebase messaging service worker in firebase-messaging-sw.js. Alternatively, you can specify an existing service worker with useServiceWorker.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM