I have integrated Firebase Web Notification using Firebase SDK.
The implementation process involves two files: a) generate-token.js and b) firebase-messaging.sw.js
- To get access token, permission is requested by calling requestPermission function.
- Upon clicking Allow, a token is generated.
- An Ajax call is made to the backend service to save the token associated with that browser.
- We have separate modules for Notification-sender and Notification-Manager to schedule and send notifications.
firebase-messaging.sw.js is located at the root level. It is invoked when a notification is triggered. There are 2 main methods in this file:
initMessaging.setBackgroundMessageHandler(function (payload) { )}; // For background handling of message
and
messaging.onMessage(function(payload) {}); : This method is placed in generate-token.js for receiving foreground messages.
When a notification is received, an ajax call is made to an API to track notification with actionId=1 and for clicking on the notification with actionId=3.
My queries:
- After saving the token in step 1, how can I reuse that token in the methods of firebase-messaging.sw.js to call the track API (which requires token and deviceId)?
- Currently, I am creating device_id using userAgent, but this approach may result in clashes with other devices. Is there a better way to handle this?
- Considering that service-workers don't have direct access to local storage, DOM, cookies, etc., how can I reuse my token effectively?
Snippet of my code:
generate-token.js:
// Code snippet for generating token
// Includes functions like requestPermission, userAction, getUniqueId, etc.
firebase-messaging.sw.js:
// Code snippet for firebase messaging service worker
// Includes handlers for push notifications, notificationclick, notificationclose, tracking notification, etc.
In order to prevent collision issues due to storing tokens with useragent as key in Firebase Database, I am looking for alternative solutions.