【问题标题】:Web foreground push notification is not popping up integrated using Firebase in ReactjsWeb 前台推送通知未弹出在 Reactjs 中使用 Firebase 集成
【发布时间】:2020-05-29 21:53:58
【问题描述】:

我在我的 reactjs Web 应用程序中使用 fcm 推送通知。如果 Web 应用程序在后台运行,我可以收到通知。但是当我的应用程序在前台主动运行时无法收到通知。

Firebase 初始化在我的项目中完美完成,因为我在后台成功获得推送通知。

firebase-messaging-sw.js

    importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-app.js');
    importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-messaging.js');

    firebase.initializeApp({
      'messagingSenderId': '337889493107'
    });
    const messaging = firebase.messaging();

    messaging.setBackgroundMessageHandler(function (payload) {
      const data = JSON.parse(payload.data.notification);
      const notificationTitle = data.title;
      const notificationOptions = {
        body: data.body,
        icon: '/favicon.png'
      };
      return self.registration.showNotification(notificationTitle,
        notificationOptions);
    });
    messaging.onMessage(function(payload) {

      const data = JSON.parse(payload.data.notification);
      const notificationTitle = data.title;
      const notificationOptions = {
        body: data.body,
        icon: '/favicon.png'
      };
      return self.registration.showNotification(notificationTitle,
        notificationOptions);
    });

我需要对我的前台方法messaging.onMessage 做任何进一步的修改还是需要做更多的配置。请帮帮我

【问题讨论】:

标签: javascript reactjs firebase firebase-cloud-messaging


【解决方案1】:

请尝试使用Notifications API,而不是 Service Worker 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.");
    } 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();
            window.open(payload.notification.click_action , '_blank');
            notification.close();
        }
    }

});

【讨论】:

    猜你喜欢
    • 2019-11-06
    • 1970-01-01
    • 2023-04-11
    • 2019-06-29
    • 2016-01-23
    • 2022-12-21
    • 2022-01-03
    • 2019-06-24
    • 1970-01-01
    相关资源
    最近更新 更多