问题
I'm trying to use FCM to send notifications to all topic subscribers. First of all, I need to subscribe the user to a topic. What I do (I'm using JavaScript Firebase Cloud Messaging for web push notifications):
1) Get FCM instance
var messaging = firebase.messaging();
2) Get token
messaging.getToken();
3) Send token to server by ajax
4) Subscribe the client to a topic from a server
https://iid.googleapis.com/iid/v1/IID_TOKEN/rel/topics/TOPIC_NAME
So, my js code is smth like this:
var messaging = firebase.messaging();
messaging.useServiceWorker(reg);
messaging.requestPermission()
.then(function () {
messaging.getToken()
.then(function (currentToken) {
if (currentToken) {
$.ajax({
type : 'POST',
url : URL_TO_SERVER_METHOD
data : {
token : currentToken
}
});
}
})
})
Then, if I make a request to https://fcm.googleapis.com/fcm/send with all necessary parameters, I get a notification in my browser. Everything works fine, but I've read from fcm docs that tokens are refreshed sometimes by an fcm app. This means if the token was refreshed, but the user wasn't resubscribed with that new token, he wouldn't get notifications.
- Question #1:
How can I be sure my subscribers always get notifications?
- Question #2:
I've seen something about the onTokenRefresh method, but will it be called when a browser is closed or computer is turned off (I'm sure, no)? And how can a simulate token refresh action?
- Question #3:
I can do subscription only once (next times with the same token aren't needed), but I don't know if my token is old and I have to resubscribe current user. What should I do this case (it's related to previous questions)?
回答1:
To make sure your users are always subscribed you definitely need to use the onTokenRefresh method. onTokenRefersh will only get triggered when the user has a new token.
The code will look something like that
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);
});
});
来源:https://stackoverflow.com/questions/48149331/fcm-subscribe-to-topic