通过铁通知-ajax(聚合物)

Notification via iron-ajax (Polymer)

我们可以使用 iron-ajax 元素在 PolymerJS 中发送通知吗?

这是 CURL 请求的示例(工作正常):

curl --header "Authorization: key=my_key" --header "Content-Type: application/json" -d '{"to": "my_token", "notification": {"title": "Hello Bro", "body": "Message Yo man"}}' https://fcm.googleapis.com/fcm/send

我正在为 "my_key" 和 "my_token" 实例使用我自己的值。在 chrome 它给了我这样的东西:Screenshot sample

这是我的 iron-ajax 元素的代码示例:

<iron-ajax id="xhr"
    auto
    url="https://fcm.googleapis.com/fcm/send"
    headers='{"Authorization": "[[my_key]]"}'
    handle-as="json"
    content-type="application/json"
    body='{"to":"[[my_token]]","notification": {"title": "Hello Bro", "body": "Message Yo man"}}' 
    method="POST">
</iron-ajax>

基于与页面上某些元素的交互,我尝试通过 JS 触发通知:

this.$.xhr.generateRequest();

我收到这样的回复:

{"multicast_id":5623718911822310219,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1489155273403695%e609af1cf9fd7ecd"}]}

看来是成功了,虽然这次我没有收到任何通知。我在这里遗漏了什么,或者是否有更好的方法在 Polymer 中实现它?预先感谢您对此事的任何见解!

它按原样运行;) 您无法通过自己的 UI 向自己发送通知。此外,如果您要向特定 app/website(至少通过桌面)发送通知 - app/website 不应该是浏览器中的当前活动选项卡(或者浏览器不应该是您的活动应用程序接收器),这当然是有道理的——但我花了一些时间才弄明白。虽然再次有更简单的方法通过 vanilla js 执行此操作 - 您甚至可以通过浏览器控制台触发它(使用正确的参数)。我希望这对某人有所帮助,祝你好运!

 function triggerNotification(key,token,title,message){
    var notification = {
      'title': title,
      'body': message
    };

    fetch('https://fcm.googleapis.com/fcm/send', {
      'method': 'POST',
      'headers': {'Authorization': 'key=' + key, 'Content-Type': 'application/json'},
      'body': JSON.stringify({'notification': notification, 'to': token})
    }).then(function() {
      console.log("Response: ",arguments);
    }).catch(function(error) {
      console.error(error);
    })
}