Files
hossein-por-shop/frontend/public/sw.js
T
2025-03-06 22:57:07 +03:30

76 lines
2.0 KiB
JavaScript

import { precacheAndRoute } from "workbox-precaching";
// Precaching configuration for PWA assets
precacheAndRoute(self.__WB_MANIFEST);
// Version
const VERSION = "1.0.423";
// Service Worker Installation
self.addEventListener("install", (event) => {
self.skipWaiting();
// Clear old cache during install
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cache) => {
if (cache !== self.registration.scope + "::" + VERSION) {
return caches.delete(cache);
}
})
);
})
);
});
// Service Worker Activation
self.addEventListener("activate", (event) => {
event.waitUntil(
(async () => {
const clients = await self.clients.matchAll({ type: "window" });
clients.forEach((client) => {
client.postMessage({
type: "VERSION_CHECK",
version: VERSION,
});
});
self.clients.claim();
})()
);
});
// Push Notification Handler for Django Web Push
self.addEventListener("push", (event) => {
try {
const payload = event.data?.json() || {
title: "New Notification",
body: "You have a new message",
icon: "/logo-192x192.png",
data: { url: "/" },
};
event.waitUntil(
self.registration.showNotification(payload.title, {
body: payload.body,
icon: payload.icon || "/logo-192x192.png",
data: payload.data,
})
);
} catch (error) {
console.error("Push handling failed:", error);
}
});
// Notification Click Handler
self.addEventListener("notificationclick", (event) => {
event.notification.close();
event.waitUntil(clients.openWindow(event.notification.data?.url || "/"));
});
self.addEventListener("message", (event) => {
if (event.data === "SKIP_WAITING") {
self.skipWaiting();
}
});