FCM推送通知消息未显示

时间:2016-11-03 08:24:56

标签: javascript c# push-notification

我正在为Web浏览器开发推送通知控制台程序。程序可以发送通知,但只发送相同的标题和服务工作者(sw.js)javascript文件的主体。我怎样才能发送不同的标题和正文。

Service-Worker JS

self.addEventListener('push', function (event) {
    console.log('Push message', event);
    var title = 'Push message SW Js';

    event.waitUntil(
        self.registration.showNotification(title, {
            'body': 'The Message Service Worker JS',
            'icon': 'images/icon.png'
        });
    );
});

程序

var data = new
{
    to = FcmDeviceID,
    notification = new
    {
        body = " Message Body ",
        title = " Message Title"
    }
};

WebRequest tRequest = WebRequest.Create(FcmUrl);
tRequest.Method = "post";
tRequest.Headers.Add(string.Format("Authorization: key={0}", FcmApiKey));
tRequest.Headers.Add(string.Format("Sender: id={0}", FcmSenderID));
tRequest.ContentType = "application/json";
string jsonss = Newtonsoft.Json.JsonConvert.SerializeObject(data);

Byte[] byteArray = Encoding.UTF8.GetBytes(jsonss);
tRequest.ContentLength = byteArray.Length;

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 sResponseFromServer = tReader.ReadToEnd();
                Console.Write(sResponseFromServer);            
            }           
        }
    }
}

1 个答案:

答案 0 :(得分:1)

服务工作者JS需要获取服务器以获取由服务器管理的标题和正文。

self.addEventListener('push', function(event) {  
  event.waitUntil(
    self.registration.pushManager.getSubscription().then(function(subscription) {
      var notificationsPath = 'yourServerURL?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(error) {  
        console.error('Unable to retrieve the server.', error);
      });
    })
  );  
});