Teja Reddy
Teja Reddy

Reputation: 119

Monitor Refresh Token for web push FCM and replace that with the old one in DB

Currently I am trying to do a web push ( Push notifications ) NOT APP only though browser

I have generated the Application Token Token generated

Then saving that token to db. Now, issues is when I clear my cache the token changes. How can I monitor thus replacing the new token with old one(replace only that particular token)?

Here is current code 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);
  });

Upvotes: 5

Views: 4442

Answers (2)

mouhammed
mouhammed

Reputation: 954

A workaround is to use the local storage to save the first token

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.');
 }
});

In the refresh context, you could retrieve the previously saved token to replace it by the new one.

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 598847

As stated in the documentation on monitoring token refresh:

The onTokenRefresh callback fires whenever a new token is generated, so calling getToken in its context ensures that you are accessing a current, available registration token.

// 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);
  });
});

Upvotes: 1

Related Questions