目前我正在尝试通过浏览器进行网络推送(推送通知)NOT APP
我已经生成了应用程序令牌 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);
});
答案 0 :(得分:0)
如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); }); });
答案 1 :(得分:0)
一种解决方法是使用本地存储来保存第一个令牌
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.');
}
});
在刷新上下文中,您可以检索以前保存的令牌以将其替换为新令牌。