如果浏览器在后台,FCM 推送通知会到达两次

我已经建立了一个简单的推送通知站点,如果浏览器在前台,通知就可以到达.

I've set up a simple push notification site, the notifications arrive okay if the browser is in foreground.

如果浏览器在后台,问题就开始了:通知到达两次,一次设置了图像样式和其他设置,另一次只有标题和正文消息.

The problem begins if the browser is in background: the notification arrives twice, one styled with image and other settings set and the other has only title and body message.

Service Worker 的内容:

Content of the service worker:

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

// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
    'messagingSenderId': '...'
});

const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function(payload) {
    console.log('[firebase-messaging-sw.js] Received background message ', 
    return null;
});

self.addEventListener('install', function (event) {
    event.waitUntil(skipWaiting());
});

self.addEventListener('activate', function (event) {
    event.waitUntil(clients.claim());
});

self.addEventListener('push', function (event) {
    var pushData = event.data.json();
    try {
        var notificationData = pushData.data;
        notificationData.data = JSON.parse(notificationData.data);
        console.log(notificationData);
        self.registration.showNotification(pushData.notification.title, notificationData);
    }
    catch (err) {
        console.log('Push error happened: ', err);
    }
});

客户端js:

firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();

messaging.onMessage(function (payload) {
    console.log("notification recieved");
    return null;
});

self.addEventListener('push', function (event) {
    console.log("window push stuff");
    return null;
});

谢谢!

推荐答案

messaging.setBackgroundMessageHandler 事件中加入这一行即可解决问题:

The problem can be solved with adding this line to the messaging.setBackgroundMessageHandler event:

self.registration.hideNotification();

这样,默认通知将不会显示,您必须在 self.addEventListener 事件中显示您的通知.

This way, the default notification won't show and you have to show your notification in the self.addEventListener event.

相关文章