I’m making an application using laravel as the backend and reactjs as the frontend using inertia, I’m trying to configure push notifications/browser notification in it using FCM.
Initially, they worked fine but when I got back to working on the project after some time, they didn’t work.
This is my firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging-compat.js');
const firebaseConfig = {
apiKey: process.env.VITE_APP_FIREBASE_API_KEY,
authDomain: process.env.VITE_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.VITE_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.VITE_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.VITE_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.VITE_APP_FIREBASE_APP_ID,
measurementId: process.env.VITE_APP_FIREBASE_MEASUREMENT_ID
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging.onBackgroundMessage(payload => {
console.log("Received background message ", payload);
console.log(
"[firebase-messaging-sw.js] Received background message ",
payload
);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: payload.notification.image
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
this is App.jsx
async function registerServiceWorker() {
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("../../public/firebase-messaging-sw.js")
.then(function(registration) {
console.log("Service Worker Registered!");
})
.catch(function(error) {
console.log("Service Worker Registration Failed: ", error);
});
}
}
// Call this function whenever you need to re-register the service worker
registerServiceWorker();
this is how I’m trying to get the device token:
const getDevToken = async () => {
Notification.requestPermission().then(async permission => {
console.log(permission);
if (permission === "granted") {
const token = await getToken(messaging, {
vapidKey: import.meta.env.VITE_APP_VAPID_KEY
});
console.log(token);
setData({
...data,
deviceToken: token
});
setdevToken(token);
}
});
};
I always get this error while trying to register the service worker
Uncaught (in promise) FirebaseError: Messaging: We are unable to register the default service worker. ServiceWorker script at http://127.0.0.1:8000/firebase-messaging-sw.js for scope http://127.0.0.1:8000/firebase-cloud-messaging-push-scope threw an exception during script evaluation. (messaging/failed-service-worker-registration).
I also get this:
Service Worker Registration Failed: DOMException: The operation is insecure.
I did trying checking if I had my service worker path wrong but that wasn’t the case.