Firebase浏览器通知:无法发送自定义消息

时间:2016-12-16 08:52:57

标签: asp.net-mvc firebase push-notification customization firebase-cloud-messaging

我们在ASP.NET MVC中开发了一个Web应用程序,并通过Firebase实现了浏览器通知。

通知工作正常但每次触发通知时,它始终显示与下面提到的相同的消息:

"嘿,有一个更新。请访问我们的网站"。

我们无法在通知中动态自定义消息。

曾与Google支持小组联系,但他们告诉我们要求Stack Overflow提供帮助。

如果你们因为我们陷入困境而无法继续前进而帮助我们解决问题,那将是很棒的。

请根据要求在下面找到代码:

sw.js:

use strict;

console.log('Started', self);

self.addEventListener('install', function(event) {
self.skipWaiting();  
console.log('Installed', event);
});

self.addEventListener('activate', function(event) {
console.log('Activated', event);
});

 self.addEventListener('push', function (event) {
event.waitUntil(
     self.registration.pushManager.getSubscription().then(function    (subscription) {
      var notificationsPath = 'http://localhost:11546?endpoint=' + encodeURIComponent(subscription.endpoint);
      var headers = new Headers();
      headers.append('Accept', 'application/json');
      return fetch(notificationsPath, { headers: headers }).then(function (response) {
          return response.json().then(function (notifications) {
              return Promise.all(
                notifications.map(function (notification) {
                    return self.registration.showNotification(notification.title, {
                        body: notification.body,
                        //icon: notification.icon_url
                    });
                })
              );
          });
      }).catch(function (xhr, status, error) {
          console.error('Unable to retrieve the server.', error);
      });
  })
);
});

Windows服务:

WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
            tRequest.Method = "post";
tRequest.ContentType = "application/json";
var objNotification = new
            {
                to = "fQLxHW2fzuc:APA91bEkGKWqVlmZkM_Z9rZTF5bYbytOOsHFbfg7lL1vVzb6XycWkf-0NuMSdwo7hfpSlNuVBbx7o4i-E549eVCkvBbtPEb-dohuHiKLg18ROthj6ds3QIYyZKi_dsrHBn-uNxKGOhX-",                   
                data = new
               {
                    body = "This is the message",
                   title = "This is the title"
               }

            };
string jsonNotificationFormat = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            Byte[] byteArray =       Encoding.UTF8.GetBytes(jsonNotificationFormat);
tRequest.Headers.Add(string.Format("Authorization: key={0}", "AAAA80JHkUE:APA91bG2LuMawMpo9TiWbDxbc3GBRVbERu3TyKZIbNb_jTMs5C4q_pQrjLmF5-QJFGgj3FzMthR16nFCi2qrYOlCDrPvFop1uhlqMIMEoKaJsUu7vUZjKMvwazWZFbgalKEb1uhbOCIK7YK5yotusvbwyPO60pgANw"));
 tRequest.Headers.Add(string.Format("Sender: id={0}", "1044789039425"));
            tRequest.ContentLength = byteArray.Length;
            tRequest.ContentType = "application/json; charset=UTF-8";
            using (Stream dataStream = tRequest.GetRequestStream())
            {
                dataStream.Write(byteArray, 0, byteArray.Length);

                using (WebResponse tResponse = tRequest.GetResponse())
                {
                    using (Stream dataStreamResponse = tResponse.GetResponseStream())
                    {
                        using (StreamReader tReader = new StreamReader(dataStreamResponse))
                        {
                            String responseFromFirebaseServer = tReader.ReadToEnd();

                            FCMResponse response = Newtonsoft.Json.JsonConvert.DeserializeObject<FCMResponse>(responseFromFirebaseServer);
                            if (response.success == 1)
                            {
                                //new NotificationBLL().InsertNotificationLog(dayNumber, notification, true);
                            }
                            else if (response.failure == 1)
                            {
                                //new NotificationBLL().InsertNotificationLog(dayNumber, notification, false);
                                //sbLogger.AppendLine(string.Format("Error sent from FCM server, after sending request : {0} , for following device info: {1}", responseFromFirebaseServer, jsonNotificationFormat));

                            }

                        }
                    }

                }
            }


manifest.json:

{
  "name": "MVCNotificationsAPI",
  "gcm_sender_id": "1044789039425"
}


main.js

if ('serviceWorker' in navigator) {
console.log('Service Worker is supported');
navigator.serviceWorker.register('../sw.js').then(function () {
    return navigator.serviceWorker.ready;
}).then(function (reg) {
    console.log('Service Worker is ready :^)', reg);

    reg.pushManager.subscribe({ userVisibleOnly: true }).then(function (sub) {
        console.log('endpoint:', sub.endpoint);
        document.getElementById("Hidden1").value = sub.endpoint;
    });
}).catch(function (error) {
    console.log('Service Worker error :^(', error);
});

}

我们遇到的问题是,我们无法动态更改下面提到的代码部分的数据:

  data = new
               {
                    body = "This is the message",
                   title = "This is the title"
               }

每当我们动态设置数据时,通知都不会被触发,我们的IDE或Firebase帐户也没有出现任何错误。

0 个答案:

没有答案