gpt4 book ai didi

javascript - FCM 推送通知消息不显示

转载 作者:行者123 更新时间:2023-12-03 05:44:14 27 4
gpt4 key购买 nike

我正在为网络浏览器开发推送通知控制台程序。程序可以发送通知,但只能发送与 service-worker(sw.js) javascript 文件相同的标题和正文。我怎样才能发送不同的标题和正文。

服务 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);
}
}
}
}

最佳答案

Service-worker 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);
});
})
);
});

关于javascript - FCM 推送通知消息不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40396755/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com