【问题标题】:Monitor Refresh Token for web push FCM and replace that with the old one in DB监控网络推送 FCM 的刷新令牌并将其替换为数据库中的旧令牌
【发布时间】:2017-06-06 12:50:22
【问题描述】:

目前我正在尝试通过浏览器进行网络推送(推送通知)而不是应用程序

我已生成应用程序令牌 Token generated

然后将该令牌保存到 db。现在,问题是当我清除缓存时令牌更改。如何监控从而用旧令牌替换新令牌(仅替换该特定令牌)?

这是当前代码 app.js

var config = {
    apiKey: "xxxxxxxx",
    authDomain: "*********",
    databaseURL: "*********",
    projectId: "t********",
    storageBucket: "******",
    messagingSenderId: "******"
  };
  firebase.initializeApp(config);

  const messaging = firebase.messaging();

  messaging.requestPermission()
  .then(function(){

    console.log("have permission");
    alert("have permission");

    return messaging.getToken();
  })
  .then(function(token){
    console.log(token);
    var newToken = token;
   alert("newToken");
  })
  .catch(function(err){

console.log("error Occurred");
alert("error occurred");

  })

  messaging.onMessage(function(payload){
console.log("onMessage",payload);
  });

【问题讨论】:

    标签: javascript firebase firebase-cloud-messaging


    【解决方案1】:

    documentation on monitoring token refresh中所述:

    每当生成新令牌时都会触发onTokenRefresh 回调,因此在其上下文中调用getToken 可确保您访问的是当前可用的注册令牌。

    // Callback fired if Instance ID token is updated.
    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);
      });
    });
    

    【讨论】:

    • 感谢您的回复..我确实尝试过,但是当我清除历史记录时它没有被触发,因此将令牌更新为新的......它没有被触发。我需要的地方把这段代码放上去
    • 此代码会在令牌刷新时触发。那是 not 在每次页面加载时。当您将代码添加到现有页面时,令牌已经存在 - 因此代码不会触发。这就是为什么你需要你已经拥有的then()
    • 当我清除缓存时,我可以清楚地看到令牌在控制台中刷新,但该功能没有触发..任何其他想法
    • 我可以理解 Android 应用的令牌何时刷新,但该事件何时在 web js-app 中发生?
    • 有什么方法可以在刷新上下文中获取旧令牌?
    【解决方案2】:

    一种解决方法是使用本地存储来保存第一个令牌

    Notification.requestPermission().then(function(permission) {
      if (permission === 'granted') {
        console.log('Notification permission granted.');
        // TODO(developer): Retrieve an Instance ID token for use with FCM.
       // Save token in the local storage
      } else {
        console.log('Unable to get permission to notify.');
     }
    });
    

    在刷新上下文中,您可以检索先前保存的令牌以将其替换为新令牌。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2016-09-24
      • 2021-11-01
      • 1970-01-01
      • 2017-10-23
      • 2015-02-27
      相关资源
      最近更新 更多