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

Der*_*rek 11 javascript firebase firebase-cloud-messaging

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

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

谢谢你的时间!

wai*_* yu 27

通过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();
        }
    }
});
Run Code Online (Sandbox Code Playgroud)


小智 11

由于通知在 Android 中已弃用,您应该使用 Firebase serviceWorker 注册来显示通知。

截至 2020 年 2 月,Firebase 似乎将其 serviceWorker 注册到“/firebase-cloud-messaging-push-scope”范围(可以在 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
        )
    });
});
Run Code Online (Sandbox Code Playgroud)