1
+ // Import the functions you need from the SDKs you need
2
+ import * as firebase from "firebase/app" ;
3
+ import { getMessaging , getToken , onMessage } from 'firebase/messaging' ;
4
+ // TODO: Add SDKs for Firebase products that you want to use
5
+ // https://firebase.google.com/docs/web/setup#available-libraries
6
+
7
+ const firebaseCloudMessaging = {
8
+ //checking whether token is available in indexed DB
9
+ tokenInlocalforage : async ( ) => {
10
+ return localStorage . getItem ( 'fcm_token' )
11
+ } ,
12
+ //initializing firebase app
13
+ init : async function ( ) {
14
+ if ( ! firebase . getApps ( ) . length ) {
15
+ firebase . initializeApp ( {
16
+ apiKey : process . env . NEXT_PUBLIC_FIREBASE_API_KEY ,
17
+ authDomain : process . env . NEXT_PUBLIC_FIREBAE_AUTH_DOMAIN ,
18
+ projectId : process . env . NEXT_PUBLIC_FIREBASE_PROJECT_ID ,
19
+ storageBucket : process . env . NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET ,
20
+ messagingSenderId : process . env . NEXT_PUBLIC_FIREBASE_MESSAGING_ID ,
21
+ appId : process . env . NEXT_PUBLIC_FIREBASE_APP_ID ,
22
+ measurementId : process . env . NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID ,
23
+ } )
24
+
25
+ try {
26
+ const messaging = getMessaging ( )
27
+ const tokenInLocalForage = await this . tokenInlocalforage ( )
28
+ //if FCM token is already there just return the token
29
+ if ( tokenInLocalForage !== null ) {
30
+ return tokenInLocalForage
31
+ }
32
+ //requesting notification permission from browser
33
+ const status = await Notification . requestPermission ( )
34
+ if ( status && status === 'granted' ) {
35
+ //getting token from FCM
36
+ const fcm_token = await getToken ( messaging , {
37
+ vapidKey : 'BC-1yQLXhWuv5Dfs90bL3iHxFLzzsTwFFqXO4vErr4a0s-fxgPJ56EqvjVyNEyIJnFCIrVXyeOgVDHl2qATMDhc'
38
+ } )
39
+ if ( fcm_token ) {
40
+ //setting FCM token in indexed db using localforage
41
+ localStorage . setItem ( 'fcm_token' , fcm_token )
42
+ console . log ( 'fcm token' , fcm_token )
43
+ //return the FCM token after saving it
44
+ return fcm_token
45
+ }
46
+ }
47
+ } catch ( error ) {
48
+ console . error ( error )
49
+ return null
50
+ }
51
+ }
52
+ } ,
53
+ getMessage : async function ( ) {
54
+ if ( firebase . getApps ( ) . length > 0 ) {
55
+ try {
56
+ const messaging = getMessaging ( ) ;
57
+ onMessage ( messaging , ( payload ) => {
58
+ console . log ( "Message Received" , payload )
59
+ } )
60
+
61
+ } catch ( error ) {
62
+
63
+ }
64
+ }
65
+ }
66
+ }
67
+ export { firebaseCloudMessaging }
0 commit comments