从不显示Firebase Web Push背景消息

时间:2018-12-03 10:18:35

标签: javascript firebase firebase-cloud-messaging

我正在Web应用程序中使用Firebase Web推送通知。

当应用程序未激活或打开时,从不显示从FCM发送的消息。没有错误产生。

前端代码:

<script src="https://www.gstatic.com/firebasejs/5.6.0/firebase.js"></script>
    <script>
        MsgElem = document.getElementById("msg")
        TokenElem = document.getElementById("token")
        NotisElem = document.getElementById("notis")
        ErrElem = document.getElementById("err")
        // Initialize Firebase
        // TODO: Replace with your project's customized code snippet
        var config = {
            apiKey: "<apikey>",
            authDomain: "<app>.firebaseapp.com",
            databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
            storageBucket: "<app>.appspot.com",
            messagingSenderId: "<id>",
        };
        firebase.initializeApp(config);

        const messaging = firebase.messaging();
        messaging
            .requestPermission()
            .then(function () {
                MsgElem.innerHTML = "Notification permission granted." 
                console.log("Notification permission granted.");

                // get the token in the form of promise
                return messaging.getToken()
            })
            .then(function(token) {
                TokenElem.innerHTML = "token is : " + token
            })
            .catch(function (err) {
                ErrElem.innerHTML =  ErrElem.innerHTML + "; " + err
                console.log("Unable to get permission to notify.", err);
            });

        messaging.onMessage(function(payload) {
            console.log("Message received. ", payload);
            NotisElem.innerHTML = NotisElem.innerHTML + JSON.stringify(payload) 
        });
    </script>

firebase-messaging-sw.js

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

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

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

    const messaging = firebase.messaging();

    messaging.setBackgroundMessageHandler (function(payload) {

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

     const data = payload.data;
     const notificationTitle = data.title;
     const notificationOptions = {
body: data.body
     };

      return self.registration.showNotification (notificationTitle,  notificationOptions);
    });

FCM请求:

 {
      "to":"ids",
      "data":{
      "body":"clicktoaction",
      "title":"Simplext Notification"
      }
    }

无论应用程序位于前台还是后台,都始终调用事件消息。onMessage(函数(有效负载)。

我尝试将FCM请求从“数据”更改为“通知”。还是一样。

我正在使用Chrome v 70。

1 个答案:

答案 0 :(得分:0)

我终于发现firebase客户端应用程序应位于https下,以便服务人员可以工作。