Firebase Messaging Js Sdk Insights : getToken() : Part 2

Kumar Swapnil
2 min readMar 10, 2019

After getting the VAPID key, it calls the getPushSubscription() method which either returns an existing subscription object or a new one if it does not exists.

After getting subscription object, it fetches FCM token details from Service Worker Scope by calling the getTokenDetailsFromSWScope() method of the tokenDetails Model (class) which Given a service worker scope, will look up the details in indexedDB and returns the details assosiated with that token.

The validateInputs function called inside the above function just makes some basic checks like type and length and throw error in case of any invalidation. Now, the last part comes. Once tokenDetails and pushSubscription details is retrieved, it either calls getNewToken() or manageExistingToken() based on the value of tokenDetails.

manageExistingToken is triggered if there’s an existing FCM token in the database and it can take 3 different actions:

  • Retrieve the existing FCM token from the database.
  • If VAPID details have changed: Delete the existing token and create a new one with the new VAPID key.
  • If the database cache is invalidated (which should happen once every week): Send a request to FCM to update the token, and to check if the token is still valid on FCM-side.

The above function is a part of base-controller. The updateToken will get the updated token from FCM server. It may or may not be the same as the existing FCM token (depends upon the validity of token). The code for updateToken is below (from base-controller).

The saveTokenDetails is saving the token details to the indexedDB. It is ultimately calling the below function of db-interface class.

Similarly, the saveVapidDetails saves the VAPID details to the indexedDB. If anything goes wrong during this token updation process, the token details is simply wiped out completely from indexedDB and unsubscribed from FCM server.

The function deleteTokenFromDB() called from manageExistingToken() just deletes token details from indexedDB and unsubscribes the token by calling FCM API. The last of manageExistingToken() is calling the same function as getToken() to fetch a new token.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Kumar Swapnil
Kumar Swapnil

Written by Kumar Swapnil

Wallflower | Tsundoku | ❣️ anime and crypto

No responses yet

Write a response