如果浏览器在后台,FCM 推送通知会到达两次 [英] FCM Push notifications arrive twice if the browser is in background

查看:21
本文介绍了如果浏览器在后台,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.

这篇关于如果浏览器在后台,FCM 推送通知会到达两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆