如何从FireBase

时间:2018-01-15 17:42:40

标签: javascript ajax firebase firebase-realtime-database firebase-notifications

我正在使用Firebase实施Firebase Web通知。

整个过程是:

有两个文件:a)generate-token.js b)firebase-messaging.sw.js

  1. 获取访问令牌的权限(通过调用requestPermission)。
  2. 单击“允许”后,将生成令牌。
  3. 对后端服务进行Ajax调用,以保存与该浏览器对应的令牌。
  4. 我们为通知发件人和通知管理员提供单独的模块来安排和发送通知。
  5. firebase-messaging.sw.js是root用户。调用通知时调用它。 有两种主要方法:

    initMessaging.setBackgroundMessageHandler(function (payload) {
    )}; ( For background handling of message)
    

    messaging.onMessage(function(payload) {}); : This method is in generate-token.js for receiving foreground message.
    
  6. 收到通知后,会向api发出ajax调用,以跟踪actionId = 1的通知以及点击通知actionId = 3。

  7. 我的问题:

    1. 在步骤1中,一旦我进行了ajax调用以保存令牌,我必须在我的firebase-messaging.sw.js方法中重用该令牌来命中跟踪api(Track api require token和deviceId)
    2. 目前,我正在使用userAgent制作device_id,这可能会与其他一些机器发生冲突。还有更好的方法吗?
    3. 如何重用我的令牌,因为服务工作者无权访问本地存储,DOM,cookie等?
    4. 我的代码:

      生成-token.js:

      firebase.initializeApp(config);
      
      const messaging=firebase.messaging();
      var postURL=null;
      var gcmId=null;
      var id=getUniqueId();
      var id1=id.split('.').join("");
      
      if ('serviceWorker' in navigator) {
          // Register service worker
          navigator.serviceWorker.register('/firebase-messaging-sw.js').then(function (reg) {
              console.log("SW registration succeeded. Scope is " + reg.scope);
              console.log("Updating service worker" +reg.update());
          }).catch(function (err) {
              console.error("SW registration failed with error " + err);
          });
      }
      
      messaging.onMessage(function(payload) {
      
          console.log("OnMessage called app is in foreground");
      
          //tracking notification with actionid=1;
          trackNotification(payload.data,1,postURL,gcmId);
      });
      
      function requestPermission(url) {
      
          console.log('Requesting permission...');
          postURL=url;
      
          var firebaseRefUrl=firebase.database().ref().child(location.host.split('.').join("")+"/" + "url");
      
          firebaseRefUrl.set(url);
      
          messaging.requestPermission()
          .then(function () {
              console.log('Notification permission granted.');
              return messaging.getToken();
          })
          .then(function(token){
      
              userAction(token,url);
              var firebaseRefToken=firebase.database().ref().child(location.host.split('.').join("") + "/" + id1);
      
              firebaseRefToken.set(token);
              gcmId=token;
      
      
          })
          .catch(function (err) {
              console.log('Unable to get permission for notification.', err);
          });
      }
      
      function getUniqueId(){
      
          var Sys = {};
          var ua = navigator.userAgent.toLowerCase();
      
          return ua;
      }
      function userAction(token,url) {
      
          try{
              console.log("Calling wrapper interface to save gcm_id");
              var obj = new Object();
              obj.deviceId =getUniqueId();
              obj.token=token;
              var jsonString= JSON.stringify(obj);
      
              var xhttp = new XMLHttpRequest();
              xhttp.open("POST", url+ "/registerGCM", true);
              xhttp.setRequestHeader("Content-type", "application/json");
      
              xhttp.send(jsonString);
              xhttp.onreadystatechange = function() {
                  if(xhttp.readyState == XMLHttpRequest.DONE && xhttp.status == 200) {
                      var jsonDeviceId=JSON.parse(xhttp.responseText);
                      localStorage.setItem("deviceId",jsonDeviceId.deviceId); 
                  }
              }
      
      
      
          }catch(error) {
              console.log('Error while calling apis.', error);
          }}
      

      火力-messaging.sw.js:

      firebase.initializeApp(config);
      
      var click=null;
      
      var url;
      var token;
      var obj=new Object();
      
      
      
      //Initialise firebase messaging
      const initMessaging = firebase.messaging();
      
      var id=getUniqueId();
      var id1=id.split('.').join("");
      
      
      var firebaseRefToken=firebase.database().ref().child(location.host.split('.').join("") + "/" + id1);
      firebaseRefToken.on('value',function(data){
      
          token=data.val();
      });
      
      
      var firebaseRefUrl=firebase.database().ref().child(location.host.split('.').join("") +"/" + "url");
      
      firebaseRefUrl.on('value',function(data){
      
          url=data.val();
      });
      
      //Background push notification handler. It fires up when the browser or web page in which push notification is activated are closed.
      initMessaging.setBackgroundMessageHandler(function (payload) {
      
          //console.log("In background");
          console.log("Tracking notification when the app is in background");
      
          var gcmId;
          var tokenRefCheck=firebase.database().ref().child(location.host.split('.').join("") + "/" + id1);
          tokenRefCheck.on('value',function(data){
      
              gcmId=data.val();
          });
      
          trackNotification(obj.data,1,url,null);
      
      
      });
      //Displays incoming push notification
      self.addEventListener('push', function (event) {
      
      
          console.log('Push Notification Received.');
      
      
          var eventData = event.data.text();
          obj = JSON.parse(eventData); //Parse the received JSON object.
      
          //printing payload 
          console.log("PAyload is " + JSON.stringify(obj,2,null));
      
          const title = obj.data.title;
      
          click=obj.data.targetActionData;
      
          const options = {
                  body: obj.data.body, 
                  icon: obj.data.icon,
                  click_action:obj.data.targetActionData
      
      
          };
          event.preventDefault();
          event.waitUntil(self.registration.showNotification(title, options));
      });
      
      
      //Take action when a user clicks on the received notification.
      
      self.addEventListener('notificationclick', function (event) {
      
      
      
          console.log("Notification clicked");
          event.notification.close();
          event.preventDefault(); // prevent the browser from focusing the Notification's tab
      
          trackNotification(obj.data,3,url,null);
          event.waitUntil(
      
                  clients.openWindow(click)
      
          );
      });
      
      
      self.addEventListener('notificationclose', function (event) {
      
      
      
          console.log("Notification closed");
          event.notification.close();
          event.preventDefault(); // prevent the browser from focusing the Notification's tab
      
          trackNotification(obj.data,2,url,null);
      
      });
      
      
      function trackNotification(data,actionId,url,gcmId) {
      
          try{
      
              var obj=new Object();
              console.log("Calling track notification api to save the data");
              if(actionId===1){
                  console.log("Tracking for receving notification");
      
              }
      
              if(actionId===2){
                  console.log("Tracking for closing notification");
      
              }
      
      
              if(actionId===3){
                  console.log("Tracking for clicking notification");
      
              }
              obj.deviceId =getUniqueId();
              obj.campaignId=data.campaignId;
              obj.actionTime=new Date();
      
      
              if(gcmId!=null)
                  obj.token=gcmId;
              else
                  obj.token=token;
      
      
              obj.actionId=actionId;
              obj.scheduleId=data.scheduleId;
              var jsonString= JSON.stringify(obj,2,null);
      
              /*xhttp.open("POST", postURL+ "/trackNotification", true);
              xhttp.setRequestHeader("Content-type", "application/json");
              xhttp.send(jsonString);*/
      
              console.log("Payload" + jsonString);
              fetch(url + "/trackNotification", {  
                  method: 'post',  
                  headers: {  
                      "Content-type": "application/json; charset=UTF-8"  
                  },  
                  body: jsonString
              })
              .then(function (data) {  
      
              })  
              .catch(function (error) {  
                  console.log('Request failed', error);
      
              });
      
      
          }catch(error) {
              console.log('Error while calling apis.', error);
          }}
      
      
      
      function getUniqueId(){
      
          var Sys = {};
          var ua = navigator.userAgent.toLowerCase();
      
          return ua;
      
      
      }
      

      我正在使用Firebase数据库,并使用useragent作为密钥保存令牌,但它肯定会与其他设备发生冲突。

1 个答案:

答案 0 :(得分:0)

您可以将数据保存在服务工作缓存中。

  

Service Worker API附带一个Cache接口,可以让您使用   创建按请求键入的响应存储。虽然这个界面是   用于服务工作者,它实际上暴露在窗口,和   可以从脚本中的任何位置访问。切入点是   高速缓存。

https://developers.google.com/web/ilt/pwa/caching-files-with-service-worker