首页 > 解决方案 > 使用 Firebase 通知打开链接/PWA

问题描述

我尝试在 C# 中使用 firebase 在特定设备上发送推送通知。我收到了消息,但在处理单击消息以打开 PWA/链接时遇到问题。

这是我发送通知的代码:

var notificationList = _dbContext.MapUserGameLottery.Where(x => x.LotId == lotteryId).ToList();
        foreach (var entry in notificationList)
        {
            var registrationToken = entry.NotificationToken;

            if (!string.IsNullOrEmpty(registrationToken))
            {
                var message = new Message()
                {
                    Notification = new Notification()
                    {
                        Title = "Test!",
                        Body = "Texttest"
                    },
                    Data = new Dictionary<string, string>()
                    {
                        { "page", "start" },
                        { "lotId", 1 }
                    },
                    Webpush = new WebpushConfig(){
                        FcmOptions = new WebpushFcmOptions()
                        {
                            Link= "https://mypage.com"
                        }
                    },
                    Token = registrationToken                        
                };

                var response = FirebaseMessaging.DefaultInstance.SendAsync(message).Result;
            }
        }

在我的 React 应用程序中,我有一个 firebase.js:

    import firebase from 'firebase';

const config = {
    apiKey: "**************************",
    authDomain: "*********-ea0ea.firebaseapp.com",
    projectId: "*********-ea0ea",
    storageBucket: "*********-ea0ea.appspot.com",
    messagingSenderId: "*********",
    appId: "1:*********:web:bd050b*********e1d2"
};

firebase.initializeApp(config);

export default firebase;

一个 firebase-messaging-sw.js

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

if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('../firebase-messaging-sw.js')
      .then(function(registration) {
        console.log('Registration successful, scope is:', registration.scope);
      }).catch(function(err) {
        console.log('Service worker registration failed, error:', err);
      });
    }

firebase.initializeApp({
        apiKey: "**************************",
    authDomain: "*********-ea0ea.firebaseapp.com",
    projectId: "*********-ea0ea",
    storageBucket: "*********-ea0ea.appspot.com",
    messagingSenderId: "*********",
    appId: "1:*********:web:bd050b*********e1d2"
  })

const initMessaging = firebase.messaging()

initMessaging.setBackgroundMessageHandler(function(payload) {
  console.log(payload);
});

self.addEventListener('notificationclick', (event) => {
    console.log(event)
    return event
})

以及 App.js 本身

componentDidMount() {
    if(window.location.href.indexOf("fanbingo.de") != -1){
      const messaging = firebase.messaging();
      
      messaging.onMessage(function (payload) {  
        console.log('[firebase-messaging-sw.js] On Message ', payload)  
      })  
  
      if (Notification.permission != 'granted') {
        messaging.requestPermission().then((token) => {
          return messaging.getToken()
        }).then(token => {
          console.log('new granted Token:', token);
          localStorage.setItem('INSTANCE_TOKEN', token);
        }).catch((error)=>{
          console.log("error");
        })
      }else{
        if (localStorage.getItem('INSTANCE_TOKEN') == null) {
          var token = messaging.getToken().then(token => {
            console.log('new entered Token:', token);
            localStorage.setItem('INSTANCE_TOKEN', token);
          })
        } else { 
            console.log('old Token:', localStorage.getItem('INSTANCE_TOKEN'));
        }
      }
    }

我的错在哪里?我实际上希望在单击通知后结束 onMessage 或 setBackgroundhandler 事件,但单击后没有任何反应。

标签: c#reactjsfirebasepush-notificationfirebase-cloud-messaging

解决方案


推荐阅读