You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
3.0 KiB

/* eslint-env serviceworker */
/* global workbox */
importScripts(
"https://storage.googleapis.com/workbox-cdn/releases/6.4.1/workbox-sw.js",
);
self.addEventListener("install", (event) => {
console.log("Service worker scripts importing...", event);
importScripts(
"safari-notifications.js",
"nacl.js",
"noble-curves.js",
"noble-hashes.js",
);
console.log("Service worker scripts imported.");
});
function logDbOrConsole(self, message, arg1, arg2) {
console.log(`${new Date().toISOString()} ${message}`, arg1, arg2);
let fullMessage = `${new Date().toISOString()} ${message}`;
if (arg1) {
fullMessage += `: ${JSON.stringify(arg1)}`;
}
if (arg2) {
fullMessage += ` -- ${JSON.stringify(arg2)}`;
}
// const logged =
self.logMessage(fullMessage);
// if (logged || !logged) {
// console.log(`${new Date().toISOString()} ${message}`, arg1, arg2);
// }
}
self.addEventListener("push", function (event) {
logDbOrConsole(this, "Received push event:", event);
event.waitUntil(
(async () => {
try {
let payload;
if (event.data) {
payload = JSON.parse(event.data.text());
}
const message = await self.getNotificationCount();
if (message) {
const title = payload && payload.title ? payload.title : "Message";
const options = {
body: message,
icon: payload ? payload.icon : "icon.png",
badge: payload ? payload.badge : "badge.png",
};
await self.registration.showNotification(title, options);
logDbOrConsole(self, "Notified user:", options);
} else {
logDbOrConsole(self, "No notification message.");
}
} catch (error) {
logDbOrConsole(self, "Error with push event", event, error);
}
})(),
);
});
self.addEventListener("message", (event) => {
logDbOrConsole(this, "Service worker message:", event);
if (event.data && event.data.type === "SEND_LOCAL_DATA") {
self.secret = event.data.data;
event.ports[0].postMessage({ success: true });
}
logDbOrConsole(this, "Service worker posted message.");
});
self.addEventListener("activate", (event) => {
logDbOrConsole(this, "Service worker activating...", event);
// see https://developer.mozilla.org/en-US/docs/Web/API/Clients/claim
// and https://web.dev/articles/service-worker-lifecycle#clientsclaim
event.waitUntil(clients.claim());
logDbOrConsole(this, "Service worker activated.");
});
self.addEventListener("fetch", (event) => {
logDbOrConsole(this, "Got fetch event:", event);
});
self.addEventListener("error", (event) => {
logDbOrConsole(this, "Error in Service Worker:", event);
console.error("Full Error:", event);
console.error("Message:", event.message);
console.error("File:", event.filename);
console.error("Line:", event.lineno);
console.error("Column:", event.colno);
console.error("Error Object:", event.error);
});
workbox.precaching.precacheAndRoute(self.__WB_MANIFEST);