簡體   English   中英

FCM推送通知消息不顯示

[英]FCM Push Notification Message doesn't show

我正在為Web瀏覽器開發推送通知控制台程序。 程序可以發送通知,但只能發送相同名稱和Service-Worker(sw.js)javascript文件正文。 如何發送不同的標題和正文。

服務人員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);            
            }           
        }
    }
}

服務人員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);
      });
    })
  );  
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM