3

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

Cuti
  • 131
  • 1
  • 6
  • What is your actual use case here? If you describe what you're actually trying to do, it'll be easier to help. – Michael Bleigh Oct 31 '17 at 19:12
  • I am making a WordPress plugin that send web push notifications, so I ask users to create a Firebase project. Then I ask them their server key and the javascript code they need to copy paste in the website. The messagingSenderId is part of this code. The problem is that the messagingSenderId is also required in the service worker and I don't know how to pass this variable to this file. – Cuti Nov 02 '17 at 00:59

1 Answers1

7

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;
}
Community
  • 1
  • 1
Cuti
  • 131
  • 1
  • 6