首页 > 解决方案 > messages.setBackgroundMessageHandler 未在网络中接收消息

问题描述

我正在 web 应用程序中实现 firebase 通知。当网页未激活时,我无法接收后台通知。

到目前为止我所做的是:

  1. manifest.json使用代码在根目录中 创建:{ "gcm_sender_id": "103953800507" }
  2. firebase-messaging-sw.js使用以下代码在根目录中创建文件:

importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
    importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
    
    firebase.initializeApp({
        'messagingSenderId': '11111'
    });
    
    const messaging = firebase.messaging();
    
    messaging.setBackgroundMessageHandler(function (payload) {
        //sometime receive notification in this
        debugger;
        //some code here to receive notification..
        return self.registration.showNotification(title,
            notificationOptions);
    });

  1. Home/Index页面中输入以下代码以获取权限和令牌

firebase.initializeApp({
            'messagingSenderId': '11111'
        });
        
        const messaging = firebase.messaging();
        
        messaging.requestPermission().then(function() {
            console.log('Notification permission granted.');

            messaging.getToken().then(function(currentToken) {

                if (currentToken) {
                    console.log(currentToken);
                    sendTokenToServer(currentToken); //save in database
                }
            }).catch(function(err) {
                console.log('An error occurred while retrieving token. ', err);
            });
        }).catch(function(err) {
            console.log('Unable to get permission to notify.', err);
        });
        
        messaging.onTokenRefresh(function() {
            messaging.getToken().then(function(refreshedToken) {
                sendTokenToServer(refreshedToken);
            }).catch(function(err) {
            });
        });
        
                messaging.onMessage(function (payload) {
            //receive notification here when this page is active. working fine

        });

  1. 从邮递员发送通知 在此处输入图像描述

如何在messaging.setBackgroundMessageHandler 中接收通知?

标签: javascriptfirebase

解决方案


上面提到的代码很好。问题出在app focus. 假设我有页面 p1、p2 和 p3。

p1 具有获取通知权限、获取令牌和接收前台通知的代码。我期待 p2 和 p3 页上的背景通知。

但是只有当这两个页面messaging.setBackgroundMessageHandler不在浏览器的当前焦点选项卡中时,它们才会收到通知。


推荐阅读