Set a variable messagingSenderId in service worker (Firebase)

4.2k Views Asked by At

I would like to set a variable messagingSenderId value in my service worker, not an hardcoded one. Is it possible?

I register my service worker like this:

navigator.serviceWorker.register( 'firebase-messaging-sw.js' )
.then( function( registration ) {
    messaging.useServiceWorker( registration );     
});

And in my firebase-messaging-sw.js, I initialize firebase like this

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

firebase.initializeApp({
  'messagingSenderId': 'my-id' // <- I want this to be variable
});

The problem is I can't find how to pass data to my service worker file. Any idea?

Thanks

1

There are 1 best solutions below

0
Cuti On

As mentionned, Passing state info into a service worker before 'install' answered the question. Thanks.

Here is the answer for this use case:

You need to pass the variable in the URL like so:

var myId = 'write-your-messaging-sender-id-here';
navigator.serviceWorker.register( 'firebase-messaging-sw.js?messagingSenderId=' + myId )
.then( function( registration ) {
    messaging.useServiceWorker( registration );     
});

And then, in firebase service worker (firebase-messaging-sw.js), you can get this variable like so:

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

var myId = new URL(location).searchParams.get('messagingSenderId');

firebase.initializeApp({
  'messagingSenderId': myId
});

This works. But URL.searchParams is a very new tool. It is less compatible than Firebase itself.

URL.searchParams: Chrome 51+, Firefox: 52+, Opera: unknown

Firebase: Chrome 50+, Firefox 44+, Opera 37+

So instead of:

var myId = new URL(location).searchParams.get('messagingSenderId');

I suggest using:

var myId = get_sw_url_parameters( 'messagingSenderId' );

function get_sw_url_parameters( param ) {
    var vars = {};
    self.location.href.replace( self.location.hash, '' ).replace( 
        /[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
        function( m, key, value ) { // callback
            vars[key] = value !== undefined ? value : '';
        }
    );
    if( param ) {
        return vars[param] ? vars[param] : null;    
    }
    return vars;
}