Files
base-front-project/public/sw.js
2026-04-22 08:56:11 +03:30

78 lines
2.4 KiB
JavaScript

const CACHE_NAME = "141-cache-v2";
const STATIC_ASSETS = ["/", "/manifest.webmanifest", "/logo/192px.png", "/logo/512px.png"];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then(async (cache) => {
await Promise.allSettled(
STATIC_ASSETS.map(async (url) => {
try {
const response = await fetch(url);
if (response.ok) {
await cache.put(url, response);
}
} catch (e) {
console.warn("❌ Failed to cache:", url);
}
})
);
})
);
self.skipWaiting();
});
const sendDeliveryReportAction = () => {
console.log("Web push delivered.");
};
self.addEventListener("push", function (event) {
if (event.data) {
try {
// Try to parse as JSON first
let data;
try {
data = event.data.json();
} catch (jsonError) {
// If JSON parsing fails, treat it as plain text
const text = event.data.text();
data = {
title: "Notification",
body: text,
icon: "/icon.png",
};
}
const options = {
body: data.body || "Default notification body",
icon: data.icon || "/logo/192px.png",
badge: "/badge.png",
vibrate: [100, 50, 100],
data: {
dateOfArrival: Date.now(),
primaryKey: "2",
url: data.url || "/",
},
};
event.waitUntil(
self.registration.showNotification(data.title, options).then(() => {
sendDeliveryReportAction();
})
);
} catch (error) {
console.error("Error processing push notification:", error);
}
}
});
self.addEventListener("notificationclick", function (event) {
event.notification.close();
event.waitUntil(clients.openWindow(event.notification.data.url));
});
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});