【问题标题】:Push Notifications with data on push Event带有推送事件数据的推送通知
【发布时间】:2017-02-02 01:06:30
【问题描述】:

我正在尝试使用 GCM 推送通知,能够在 Push Event 上显示带有硬编码数据或消息的通知。但是当我尝试使用数据对象作为 Json 推送自定义消息时,Push 事件正在触发,但是,数据对象总是鞋底为空。

服务工作者代码:sw.js

 self.addEventListener('push', function(event) {
 console.log('Received a push message', event);
 console.log("event data",event.data);//here data is giving as null
var data=event.data.json();
var title= data.title||'No tiltle';
 var body= data.message||'no messgae';

event.waitUntil(
self.registration.showNotification(title, {
  body: body,
  icon: icon,
  tag: tag


  })
  );
  });

我正在使用第三方网站 (requestmaker.com) 检查通知。 发送格式如下

 URL:https://android.googleapis.com/gcm/send
 content-type:application/json
 authorization:key=XXXXXXXXXX

以下是数据格式

 {
 "registration_ids":["someid"],
    "data":{"title":"hai",
    "body":"hello new message"
   }
 }

我如何在推送事件中获取数据以及我必须以哪种格式发送数据作为请求,以便我可以在推送事件(event.data)中获取该数据。

【问题讨论】:

    标签: javascript push-notification service-worker chrome-gcm


    【解决方案1】:

    您可以访问通知点击触发事件的数据。

    self.addEventListener('notificationclick', function(event) {
    
     // here data you access from event using event.notification.data
      console.log('On notification click: ', event.notification.tag);
    
    }
    

    【讨论】:

    • 想要在推送事件中显示通知,并将该数据作为消息。 'notificationclick' 事件仅在通知弹出窗口出现并且我们点击它时才会发生。
    • 检查通知是否被授予使用 (!(self.Notification && self.notification.permission === 'granted')) { return; }
    【解决方案2】:

    从触发的推送通知开始,payload 数据不会被发送到 service worker。在触发要发送的有效负载的推送通知时,您必须使用浏览器身份验证密钥。

    有关详细信息,请参阅以下文档。 https://developers.google.com/web/updates/2016/03/web-push-encryption?hl=en

    【讨论】:

    • @Nitya:实际上是按照那个链接,加密消息然后得到 200 ok 响应,但现在 Push 事件没有触发。
    • @venugopal:我曾尝试使用github.com/web-push-libs/web-push 库将有无负载发送到 Firefox 和 chrome。可以试试这个库来发送有效载荷。请尝试以下链接了解使用详情。它对体面的文档和演示非常有帮助。 serviceworke.rs/push-get-payload_server_doc.html
    • 我正在使用网络推送 java 库(github.com/MartijnDwars/web-push/blob/master/src/main/java/nl/… 它给出 200 Ok 响应,但没有触发事件。
    • var rawKey = pushSubscription.getKey ? pushSubscription.getKey('p256dh') : ''; console.log('rawkwy',rawKey); var key = rawKey ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawKey))) : ''; var rawAuthSecret = pushSubscription.getKey ? pushSubscription.getKey('auth') : ''; var authSecret = rawAuthSecret ? btoa(String.fromCharCode.apply(null, new Uint8Array(rawAuthSecret))) :
    • var content = { "registration_ids" : subId, "endpoint" :endpoint, "authKey":authKey, "PublicKey256":userkey256, "data.title":"hello" }; $.ajax({ type : "POST", url : "/callGCM", dataType : "json", data : content, success : function(data) { alert("success"); }, error : function(e) { 警报("错误"+e); }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多