Depending on the environment, I have two different configurations I would like to use (test and prod). Unfortunately, firebase only works with the one service worker in the domain root folder (/firebase-messaging-sw.js). The dev environment is in a subfolder of the domain.
What I tried is sending a message to the sw as soon as it is registered and ready with the correct config - that works. However, initializing the firebase app throws warnings if it is not done immediately (don't know why that is) and the listener messaging.onBackgroundMessage stops working.
Warnings in Console from Firebase
(.../firebasejs/messaging/src/helpers/register.ts)
- register.ts:80 Event handler of 'push' event must be added on the initial evaluation of worker script.
- register.ts:83 Event handler of 'pushsubscriptionchange' event must be added on the initial evaluation of worker script.
- register.ts:86 Event handler of 'notificationclick' event must be added on the initial evaluation of worker script.
app.js
Sending the config
navigator.serviceWorker.register('/firebase-messaging-sw.js')
.then(() => navigator.serviceWorker.ready)
.then(reg => reg.active.postMessage({ firebaseConfig }))
firebase-messaging-sw.js
This gets me the right config, but initializing firebase fails
self.addEventListener('message', ({ data }) => {
if(data?.firebaseConfig)
initFirebaseMessaging(data.firebaseConfig);
});
And this is the main part of initializing firebase
importScripts('https://www.gstatic.com/firebasejs/9.21.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.21.0/firebase-messaging-compat.js');
const initFirebaseMessaging = function(config){
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.onBackgroundMessage(message => { ... });
};
When I hard code the config for one environment in the sw file and call initFirebaseMessaging(...) right away after importing the scripts, everything works fine.
messaging.onBackgroundMessagestops working when they appear.register('/firebase-messaging-sw.js?config=test')for example, can I? Or can I use a variable defined somewhere else?