首页 > 解决方案 > Firebase sw.js 关闭浏览器后没有响应

问题描述

我创建了使用 Cloud Messaging 的 firebase 项目。到现在为止,当浏览器(chrome)打开时,我已经成功地从后端向客户端发送了一条消息,但是当我关闭浏览器通知时,直到重新打开浏览器才发送,您可以在下面的代码中看到我的 firebase-messaging-sw.js

importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-messaging.js');
firebase.initializeApp({
    messagingSenderId: "My-Sender-Id"
});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
    console.log('[firebase-messaging-sw.js] Received background message ', payload);
    // Customize notification here
    var notificationTitle = 'Background Message Title';
    var notificationOptions = {
        body: 'Background Message body.',
        icon: '/firebase-logo.png'
    };

    return self.registration.showNotification(notificationTitle,
        notificationOptions);
});
self.addEventListener('push', function(e) {
    var data;
    if (e.data) {
        data = JSON.parse(e.data.text()).data;
    } else {
        data = {};
    }
    var title = data.title;
    var options = {
        body: data.body,
        icon: 'assets/custom/img/logo.png',
        vibrate: [100, 50, 100],
        requireInteraction: true,
        data: data.data ? data.data : null,
        dir: "rtl",
        actions: [{
                action: data.action,
                title: 'open',
                icon: 'images/checkmark.png'
            },
            {
                action: 'close',
                title: 'close',
                icon: 'images/xmark.png'
            },
        ]
    };
    e.waitUntil(
        self.registration.showNotification(title, options)
    );
});
self.addEventListener('notificationclick', function(event) {
    console.log('On notification click: ', event.notification.tag);
    event.notification.close();
    if (event.action != "" && event.action != "close") {
        return clients.openWindow(event.action);
    }
});

即使浏览器关闭,我如何才能收到通知?

标签: firebasegoogle-cloud-messagingservice-worker

解决方案


我相信你正在使用 FCM 的服务工作者,服务工作者只在浏览器打开时工作,因为服务工作者负责处理推送通知,当浏览器关闭时你不会收到任何推送通知,实际上是推送通知只会在浏览器打开时出现,或者您为其配置 FCM 的应用程序在 chrome 选项卡上打开但未聚焦,有一种解决方法或您说解决方案,即确保 chrome 浏览器处于活动状态即使在关闭 chrome 浏览器后背景。

chrome设置中有选项

转到设置 -> 高级 -> 在 Google Chrome 关闭时继续运行后台应用程序,确保启用它 关闭 Google Chrome 时继续运行后台应用程序的选项

我已经测试了 FCM 的代码,启用该选项后,您将收到通知弹出窗口。


推荐阅读