发送所有用户的网络推送通知

时间:2018-01-11 11:59:34

标签: node.js angular firebase firebase-cloud-messaging firebase-notifications

到目前为止,我已经使用服务工作者,app manifest和fire-base为我的角应用创建了推送通知服务。

我正在获取服务器密钥和sender_id。我' m注册我的服务工作者并订阅push_messenger。

我也使用谷歌本地服务器扩展来托管我的服务器。

main.ts

   Notification.requestPermission(function (status) {
  console.log('Notification permission status:', status);
});


if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('./service-worker.js', { scope: './' }).then(function (registration) {
    // Registration was successful
    console.log('ServiceWorker registration successful with scope: ', registration.scope);
    console.log('registration: ', (registration));
    navigator.serviceWorker.ready.then(reg => {
      reg.pushManager.getSubscription().then(sub => {
        if (sub == undefined) {
          console.log('sub : ' + 'undefined');
          navigator.serviceWorker.getRegistration().then((reg) => {
            reg.pushManager.subscribe({
              userVisibleOnly: true
            }).then(sub => {
              console.log('sub : ' + JSON.stringify(sub));
              localStorage.setItem("sub", JSON.stringify(sub));
            }, err => {
              console.log('registration error occured: ' + err);
            })
          }, err => {
            console.log('registration error occured: ' + err);
          })
        } else {
          console.log('sub : ' + sub);
          // subs = sub;
          localStorage.setItem("sub", JSON.stringify(sub));
        }
      }, err => {
        console.log('registration error occured: ' + err);
      });

    })
  }).catch(function (err) {
    // registration failed :(
    console.log('ServiceWorker registration failed: ', err);
  });
}

服务worker.js

self.addEventListener('notificationclose', function(e) {
  var notification = e.notification;
  var primaryKey = notification.data.primaryKey;

  console.log('Closed notification: ' + primaryKey);
});

self.addEventListener('notificationclick', function(e) {
  var notification = e.notification;
  var primaryKey = notification.data.primaryKey;
  var action = e.action;

  if (action === 'close') {
    notification.close();
  } else {
    clients.openWindow('samples/page' + primaryKey + '.html');
    notification.close();
  }

  // TODO - close all notifications when one is clicked

});

self.addEventListener('push', function(e) {
  var body;

  if (e.data) {
    body = e.data.text();
  } else {
    body = 'Push message no payload';
  }

  var options = {
    body: body,
    icon: 'images/notification-flat.png',
    vibrate: [100, 50, 100],
    data: {
      dateOfArrival: Date.now(),
      primaryKey: 1
    },
    actions: [
      {action: 'explore', title: 'Explore this new world',
        icon: 'images/checkmark.png'},
      {action: 'close', title: "I don't want any of this",
        icon: 'images/xmark.png'},
    ]
  };
  e.waitUntil(
    self.registration.showNotification('Push Notification', options)
  );
});

节点服务器

var webPush = require('web-push');

    var pushSubscription = {<subscription object>}

    };


    var payload = 'Sup Dude!';

    var options = {
      gcmAPIKey: *<server key>*,
      TTL: 60,


    };

    webPush.sendNotification(
      pushSubscription,
      payload,
      options
    );

在上面的main.ts中,当应用程序初始化时,我能够获得订阅对象。并能够在那一刻发送推送通知。但是当我从chrome打开这个相同的服务器IP时,我得到了一个不同的订阅对象。有时我会使用chrome获得不同的订阅对象

问题是如何为所有用户发送推送通知,因为订阅对象随时间不同,浏览器与浏览器不同。 (不能将所有数据存储到数据库中,这将是过多的存储空间)

2 个答案:

答案 0 :(得分:0)

我认为你应该为此目的使用FCM。您可以在哪里创建组并向所有组发送通知。但即使是创建组,您也需要为每个设备使用deviceId。

您可以在后端存储所有这些ID,并向所有人发送FCM网络推送。

https://firebase.google.com/docs/cloud-messaging/js/client

您可以通过FCM文档实现此目的。

答案 1 :(得分:0)

This is official firebase cloud-messaging documention非常有用......!

也可以在以下链接结帐,

firebase cloud-messaging google

firebase cloud-messaging staring(订阅此频道)

这是我在客户端进行推送通知令牌注册的工作代码,可能适合您

<script>
        messaging.requestPermission()
            .then(function() {
                        console.log('Notification permission granted.');
                        // TODO(developer): Retrieve an Instance ID token for use with FCM.
                        messaging.getToken()
                            .then(function(currentToken) {
                                if (currentToken) {
                                    console.log(currentToken);
                                    settingTokenToServer(currentToken);
                                } else {    
                                    // Show permission request.
                                    console.log('No Instance ID token available. Request permission to generate one.');
                                    setTokenSentToServer(false);
                                    refreshToken();
                                }
                            })
                            .catch(function(err) {
                                console.log('An error occurred while retrieving token............................... ', err);
                            });
                    })
                    .catch(function(err) {
                        console.log('Unable to get permission to notify.', err);
                    }); 
    messaging.onTokenRefresh(function() {
        messaging.getToken()
            .then(function(refreshedToken) {
                console.log('Token refreshed.');
                // Indicate that the new Instance ID token has not yet been sent to the
                // app server.
                setTokenSentToServer(false);
                // Send Instance ID token to app server.
                sendTokenToServer(refreshedToken);
                // ...
            })
            .catch(function(err) {
                console.log('Unable to retrieve refreshed token ', err);
                showToken('Unable to retrieve refreshed token ', err);
            });
    });


    function settingTokenToServer(subscription_id) {
        if (!isTokenSentToServer()) {
            //setting token to FCM server
            var ref = firebase.database().ref("notes/token");
            ref.push({subscription_id}).then(function() {
                console.log("Token saved Successfully..!");
            }).catch(function(error) {
                alert("Token not saved..." + error);
            });

            setTokenSentToServer(true);
        } else {
            console.log('Token already sent to server so won\'t send it again unless it changes');
        }
    }

    function isTokenSentToServer() {
        return window.localStorage.getItem('sentToServer') == 1;
    }

    function setTokenSentToServer(sent) {
        window.localStorage.setItem('sentToServer', sent ? 1 : 0);
    }
</script>