Firebase onMessage未触发

时间:2020-02-07 12:28:19

标签: javascript firebase firebase-cloud-messaging

我在使用Firebase推送通知时遇到问题。 onMessage事件未触发

firebase-messaging-sw.js

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

firebase.initializeApp({
    apiKey: "some_data",
    authDomain: "some_data",
    databaseURL: "some_data",
    projectId: "some_data",
    storageBucket: "some_data",
    messagingSenderId: "some_data",
    appId: "some_data",
    measurementId: "some_data"
});

var messaging = firebase.messaging();

messaging.onMessage(function(payload) {
     console.log('Message received. ', payload);
 });

index.html

<script src="https://www.gstatic.com/firebasejs/7.8.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.8.1/firebase-messaging.js"></script>

<script>
    firebase.initializeApp({
        apiKey: "some_data",
        authDomain: "some_data",
        databaseURL: "some_data",
        projectId: "some_data",
        storageBucket: "some_data",
        messagingSenderId: "some_data",
        appId: "some_data",
        measurementId: "some_data"
    });

    if ('Notification' in window) {
        navigator.serviceWorker.register("js/firebase-messaging-sw.js")
        .then((registration) => {
            var messaging = firebase.messaging();
            messaging.useServiceWorker(registration);
            console.log(messaging);
            if (Notification.permission === 'granted') {
                subscribe(messaging);
                messaging.onMessage(function(payload) {
                     console.log('Message received. ', payload);
                 });
            }

            $('#subscribe').on('click', function () {
                subscribe(messaging);
            });
        });

    }

    function subscribe(messaging) {
        messaging.requestPermission()
            .then(function () {
                messaging.getToken()
                    .then(function (currentToken) {
                        console.log(currentToken);

                        if (currentToken) {
                            sendTokenToServer(currentToken);
                        }
                    })
                    .catch(function (err) {
                        setTokenSentToServer(false);
                    });
        })
        .catch(function (err) {
            console.warn('not granted', err);
        });
    }

    function sendTokenToServer(currentToken) {
        if (!isTokenSentToServer(currentToken)) {
            console.log('Отправка токена на сервер...');

            var url = '';
            $.post(url, {
                token: currentToken
            });

            setTokenSentToServer(currentToken);
        }
    }

    function isTokenSentToServer(currentToken) {
        return window.localStorage.getItem('sentFirebaseMessagingToken') == currentToken;
    }

    function setTokenSentToServer(currentToken) {
        window.localStorage.setItem(
            'sentFirebaseMessagingToken',
            currentToken ? currentToken : ''
        );
    }
</script>

我能够获取令牌并将其发送到服务器。但是当我发送来自邮递员的请求

https://fcm.googleapis.com/fcm/send
{
    "notification": {
        "title": "test",
        "body": "test",
        "click_action": "http://localhost:8001/"
    },
    "to": "token"
}

我在网页上什么也看不到,也没有消息(邮递员的回复状态为200)

从Firebase获取通知的正确方法是什么?还是我做错了什么?

1 个答案:

答案 0 :(得分:1)

首先,我的邮递员要求并非绝对正确。 Firebase请求有两种类型,一种仅用于活动的浏览器选项卡,另一种可以在后台运行。我使用了第一个,这就是为什么我看不到onMessage没有触发的原因。

邮递员请求应为

https://fcm.googleapis.com/fcm/send
{
    "data": {
        "title": "test",
        "body": "test",
        "click_action": "http://localhost:8001/"
    },
    "to": "token"
}

第二,在订阅并将令牌发送到服务器之前,必须先调用messaging.usePublicVapidKey()

最后一个messaging.onMessage也必须在向服务器发送令牌之前