3

我想在我的服务工作者中设置一个变量 messingsSenderId 值,而不是硬编码的值。可能吗?

我像这样注册我的服务人员:

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

在我的 firebase-messaging-sw.js 中,我像这样初始化 firebase

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
});

问题是我找不到如何将数据传递给我的服务工作者文件。任何想法?

谢谢

4

1 回答 1

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;
}
于 2017-11-08T02:52:11.373 回答