我正在尝试本文建议的推送通知演示。 https://developers.google.com/web/updates/2015/03/push-notificatons-on-the-open-web?hl=en
并尝试从github运行代码https://github.com/GoogleChrome/samples/tree/gh-pages/push-messaging-and-notifications
根据指示,我做了以下事情 -
1.在谷歌开发者控制台上创建项目
2.在config.js中添加浏览器应用程序密钥> gcmAPIKey:'浏览器api键'
3.将gsm_sender_id:'项目编号'添加到manifest.json中
4. https://somedomain.com上的托管申请
结果是
每当我点击SendPushMessage按钮时,它都不会显示任何通知。在调试时,我发现这个请求被解雇了
https://xxsomedomainxxx.azurewebsites.net/api/get/?subscriptionId=APA91bE_xyl2sP8l1pa8j4n84VGfJgKVb28I0DJK5qo9zUVLy0ZSRsyl2BbjLDSZ-Y625LqsmMp3rIH4PW3s1v_ccBOdCbWYsxaF525FHRbx5odr-z1a1uPrP4zqy4DFlKkwa9pyHhkdxL0ggxGBbC_bB6LTZSDuTKlDeXTRhywcY9X5KxBXrxhS_4M8oJFUi3eW6FikEUiJ
根据我的观察,我需要在服务器上捕获 substriptionId 并需要对它做一些事情。那么我需要在服务器上为以下API编写什么样的代码
答案 0 :(得分:0)
我创建了一个WCF REST服务,其中包含以下代码及其向android chrome 42+发送通知。
但是这里有一个问题,通知显示来自service-worker.js文件的消息,而不是来自此代码
var value =“来自服务器的Hello”;
。我正在努力并尽快更新这个答案。
请在main.js文件中更新此功能
function getNotification(subscription) {
navigator.serviceWorker.ready.then(function (serviceWorkerRegistration) {
serviceWorkerRegistration.pushManager.subscribe()
.then(function (subscription) {
console.log('getNotification', subscription)
fetch('/pushnotificationservice.svc/sendnotification?key=' + subscription.subscriptionId).then(function (obj) {
console.log('getNotification', obj)
});
});
});
WCF服务代码
public string SendNotification(string key)
{
ServiceData myServiceData = new ServiceData();
try
{
string GoogleAppID = "2440XXXXXXXX";//put your project number here
string redId = key;
var SENDER_ID = "youremail@gmail.com";//I haven't tried with another junk value
var value = "Hello from server";//this message do not displayed in notification
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
tRequest.Headers.Add(string.Format("Authorization: key={0}", "Your browser key"));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "®istration_id=" + key + "";
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
return sResponseFromServer;
}
catch (FaultException fex)
{
myServiceData.Result = false;
myServiceData.ErrorMessage = "unforeseen error occurred. Please try later.";
myServiceData.ErrorDetails = fex.ToString();
throw new FaultException<ServiceData>(myServiceData);
}
}