I am making a library that initializes a firebase push notification. I want to achienve a hassle-free firebase configuration by letting the js to set it up for me.
import { initializeApp } from "firebase/app";
import { getMessaging, onMessage, getToken, isSupported } from "firebase/messaging";
function tokenHandle(currentToken,url) {
if (currentToken) {
console.log(currentToken);
}
}
function uponGrantedPermissionHandler(messaging,vapidKey,serviceWorkerUrl,tokenNotificationUrl,workerAsModule){
if ('serviceWorker' in navigator) {
const workerConfig = workerAsModule?{ type: 'module' }:undefined
serviceWorkerUrl = serviceWorkerUrl??"https://mycdn.com/firebase-messaging-sw.js";
navigator.serviceWorker
.register(serviceWorkerUrl, workerConfig)
.then((registration) => {
console.log(messaging)
if (registration) {
console.log('Registration successful, scope is:', registration.scope)
getToken(messaging, { vapidKey })
.then((token)=>tokenHandle(token,tokenNotificationUrl))
.catch(error => console.error(error));
}
})
.catch(function (err) {
console.log('Service worker registration failed, error:', err)
})
}
}
function pushNotificationInit(firebaseConfig,vapidKey,tokenNotificationUrl,serviceWorkerUrl,workerAsModule){
const app = initializeApp(firebaseConfig);
isSupported().then((isSupported) => {
if (!isSupported) {
throw "Browser Is not Supported"
return;
}
const messaging = getMessaging(app)
Notification.requestPermission().then(function (permission) {
console.log('permiss', permission)
if (permission === 'granted') {
uponGrantedPermissionHandler(messaging,vapidKey,serviceWorkerUrl,tokenNotificationUrl,workerAsModule)
onMessage(messaging, (payload) => {
const n = new Notification(payload.notification.title, {
body: payload.notification.body,
});
});
}
});
}).catch((error)=>console.error(error));
}
export {pushNotificationInit};
what I want to do is to have an easy api to use and be as simple as:
import {pushNotificationInit} from './firebaseLib';
pushNotificationInit(firebaseConfig,vapidKey,"",null,true)
And pushNotificationInit
to initialize the worker as well. But a common service worker for firebase is:
import { initializeApp } from 'firebase/app';
import { onBackgroundMessage,getMessaging } from 'firebase/messaging/sw'
const firebaseConfig = {
// config
};
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);
onBackgroundMessage(messaging, (payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background message body',
icon: 'icon.png'
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
What I want to do is to pass the config from core js into my service worker. Is there a way to do that?