使用前景/焦点中的页面创建Firebase通知

时间:2016-11-03 20:54:31

标签: javascript firebase firebase-cloud-messaging

使用Firebase云消息传递(适用于网络),如何生成网页关闭时或后台显示的通知,但是当我实际关注网页时?

我的理解是messaging.onMessage(...)是我在处理焦点时处理传入消息的地方,但我似乎无法找到有关如何仍然创建通知弹出窗口的文档,就好像页面是在后台。

谢谢你的时间!

3 个答案:

答案 0 :(得分:23)

通过Notification API处理传入的消息

messaging.onMessage(function(payload) {
    const notificationTitle = payload.notification.title;
    const notificationOptions = {
        body: payload.notification.body,
        icon: payload.notification.icon,        
    };

    if (!("Notification" in window)) {
        console.log("This browser does not support system notifications");
    }
    // Let's check whether notification permissions have already been granted
    else if (Notification.permission === "granted") {
        // If it's okay let's create a notification
        var notification = new Notification(notificationTitle,notificationOptions);
        notification.onclick = function(event) {
            event.preventDefault(); // prevent the browser from focusing the Notification's tab
            window.open(payload.notification.click_action , '_blank');
            notification.close();
        }
    }
});

答案 1 :(得分:8)

由于Android中不推荐使用通知,因此您应该使用Firebase serviceWorker注册来显示通知。

截至2020年2月,Firebase似乎在'/ firebase-cloud-messaging-push-scope'范围内注册了其serviceWorker(可以在chrome devtools-> Application-> Service Workers中看到)

要使用该功能,您可以执行以下操作:

messaging.onMessage(function(payload) {
    console.log("onMessage: ", payload);
    navigator.serviceWorker.getRegistration('/firebase-cloud-messaging-push-scope').then(registration => {
        registration.showNotification(
            payload.notification.title,
            payload.notification
        )
    });
});

答案 2 :(得分:0)

更干净的方法是:

messaging.onMessage(payload => {
  const {title, ...options} = payload.notification;
  navigator.serviceWorker.ready.then(registration => {
    registration.showNotification(title, options);
  });
});