Chrome没有收到fcm消息,但firefox确实如此

时间:2017-04-27 16:31:45

标签: javascript firebase firebase-cloud-messaging

我正在使用FCM来促进自定义服务工作者中的推送消息。我跟着FCM开始了,但是遇到了javascript客户端没有收到chrome上发送的消息的问题,但firefox正在按预期工作。

邮件是从托管服务器发送的,邮件的发送没有失败,邮件ID与每个注册的客户端相关联。

下面是页面脚本,下面是相关的服务工作者代码。

页面HTML

<script>
    // Initialize Firebase
    var config = {
        <CONFIG SETTINGS>
    };
    firebase.initializeApp(config);
    var messaging = firebase.messaging();
</script>
<script>
    if ('serviceWorker' in navigator) {
        window.addEventListener('load', function () {
            navigator.serviceWorker.register('/sw.js').then(function (registration) {
                console.log('ServiceWorker registration successful with scope: ', registration.scope);
                messaging.useServiceWorker(registration);
                resetUI();
            }).catch(function (err) {
                console.log('ServiceWorker registration failed: ', err);
            });
        });
    }
    const permissionDivId = 'permission_div';
    messaging.onTokenRefresh(function () {
        messaging.getToken()
            .then(function (refreshedToken) {
                console.log('Token refreshed.');
                setTokenSentToServer(false);
                sendTokenToServer(refreshedToken);
                resetUI();
            })
            .catch(function (err) {
                console.log('Unable to retrieve refreshed token ', err);
            });
    });
    messaging.onMessage(function (payload) {
        console.log("Message received. ", payload);
        appendMessage(payload);
    });
    function resetUI() {
        clearMessages();
        messaging.getToken()
            .then(function (currentToken) {
                if (currentToken) {
                    sendTokenToServer(currentToken);
                    updateUIForPushEnabled(currentToken);
                } else {
                    console.log('No Instance ID token available. Request permission to generate one.');
                    updateUIForPushPermissionRequired();
                    setTokenSentToServer(false);
                }
            })
            .catch(function (err) {
                console.log('An error occurred while retrieving token. ', err);
                setTokenSentToServer(false);
            });
    }
    function sendTokenToServer(currentToken) {
        if (!isTokenSentToServer()) {
            console.log('Sending token to server...');
            <TOKEN SENT TO SERVER AND STORED>
            setTokenSentToServer(true);
        } else {
            console.log('Token already sent to server so won\'t send it again ' +
                'unless it changes');
        }
    }
    function isTokenSentToServer() {
        if (window.localStorage.getItem('sentToServer') == 1) {
            return true;
        }
        return false;
    }
    function setTokenSentToServer(sent) {
        window.localStorage.setItem('sentToServer', sent ? 1 : 0);
    }
    function showHideDiv(divId, show) {
        const div = document.querySelector('#' + divId);
        if (show) {
            div.style = "display: visible";
        } else {
            div.style = "display: none";
        }
    }
    function requestPermission() {
        console.log('Requesting permission...');
        messaging.requestPermission()
            .then(function () {
                console.log('Notification permission granted.');
                resetUI();
            })
            .catch(function (err) {
                console.log('Unable to get permission to notify.', err);
            });
    }
    function deleteToken() {
        messaging.getToken()
            .then(function (currentToken) {
                messaging.deleteToken(currentToken)
                    .then(function () {
                        console.log('Token deleted.');
                        setTokenSentToServer(false);
                        resetUI();
                    })
                    .catch(function (err) {
                        console.log('Unable to delete token. ', err);
                    });
            })
            .catch(function (err) {
                console.log('Error retrieving Instance ID token. ', err);
            });
    }
    // Add a message to the messages element.
    function appendMessage(payload) {
        const messagesElement = document.querySelector('#messages');
        const dataHeaderELement = document.createElement('h5');
        const dataElement = document.createElement('pre');
        dataElement.style = 'overflow-x:hidden;'
        dataHeaderELement.textContent = 'Received message:';
        dataElement.textContent = JSON.stringify(payload, null, 2);
        messagesElement.appendChild(dataHeaderELement);
        messagesElement.appendChild(dataElement);
    }
    // Clear the messages element of all children.
    function clearMessages() {
        const messagesElement = document.querySelector('#messages');
        while (messagesElement.hasChildNodes()) {
            messagesElement.removeChild(messagesElement.lastChild);
        }
    }
    function updateUIForPushEnabled(currentToken) {
        showHideDiv(permissionDivId, false);
    }
    function updateUIForPushPermissionRequired() {
        showHideDiv(permissionDivId, true);
    }
</script>

sw.js

self.addEventListener('push', function (event) {
  console.log('Service Worker recived a push message', event.data.text());
  var notification = event.data.json().notification;
  var title = notification.title;
  event.waitUntil(
      self.registration.showNotification(title, {
          body: notification.body,
          icon: notification.icon,
          data: { url: notification.click_action }
      }));
});

感谢您提供任何帮助!

0 个答案:

没有答案