sw.js 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. /* eslint-disable import/no-extraneous-dependencies */
  2. import { cleanupOutdatedCaches, createHandlerBoundToURL, precacheAndRoute } from "workbox-precaching";
  3. import { NavigationRoute, registerRoute } from "workbox-routing";
  4. import { NetworkFirst } from "workbox-strategies";
  5. import { getDbAsync } from "../src/app/getDb";
  6. import { formatMessage, formatTitleWithDefault } from "../src/app/notificationUtils";
  7. // See WebPushWorker, this is to play a sound on supported browsers,
  8. // if the app is in the foreground
  9. const broadcastChannel = new BroadcastChannel("web-push-broadcast");
  10. self.addEventListener("install", () => {
  11. console.log("[ServiceWorker] Installed");
  12. self.skipWaiting();
  13. });
  14. self.addEventListener("activate", () => {
  15. console.log("[ServiceWorker] Activated");
  16. self.skipWaiting();
  17. });
  18. // There's no good way to test this, and Chrome doesn't seem to implement this,
  19. // so leaving it for now
  20. self.addEventListener("pushsubscriptionchange", (event) => {
  21. console.log("[ServiceWorker] PushSubscriptionChange");
  22. console.log(event);
  23. });
  24. self.addEventListener("push", (event) => {
  25. // server/types.go webPushPayload
  26. const data = event.data.json();
  27. console.log("[ServiceWorker] Received Web Push Event", { event, data });
  28. const { subscription_id: subscriptionId, message } = data;
  29. broadcastChannel.postMessage(message);
  30. event.waitUntil(
  31. (async () => {
  32. const db = await getDbAsync();
  33. await Promise.all([
  34. (async () => {
  35. await db.notifications.add({
  36. ...message,
  37. subscriptionId,
  38. // New marker (used for bubble indicator); cannot be boolean; Dexie index limitation
  39. new: 1,
  40. });
  41. const badgeCount = await db.notifications.where({ new: 1 }).count();
  42. console.log("[ServiceWorker] Setting new app badge count", { badgeCount });
  43. self.navigator.setAppBadge?.(badgeCount);
  44. })(),
  45. db.subscriptions.update(subscriptionId, {
  46. last: message.id,
  47. }),
  48. self.registration.showNotification(formatTitleWithDefault(message, message.topic), {
  49. tag: subscriptionId,
  50. body: formatMessage(message),
  51. icon: "/static/images/ntfy.png",
  52. data,
  53. }),
  54. ]);
  55. })()
  56. );
  57. });
  58. self.addEventListener("notificationclick", (event) => {
  59. event.notification.close();
  60. const { message } = event.notification.data;
  61. if (message.click) {
  62. self.clients.openWindow(message.click);
  63. return;
  64. }
  65. const rootUrl = new URL(self.location.origin);
  66. const topicUrl = new URL(message.topic, self.location.origin);
  67. event.waitUntil(
  68. (async () => {
  69. const clients = await self.clients.matchAll({ type: "window" });
  70. const topicClient = clients.find((client) => client.url === topicUrl.toString());
  71. if (topicClient) {
  72. topicClient.focus();
  73. return;
  74. }
  75. const rootClient = clients.find((client) => client.url === rootUrl.toString());
  76. if (rootClient) {
  77. rootClient.focus();
  78. return;
  79. }
  80. self.clients.openWindow(topicUrl);
  81. })()
  82. );
  83. });
  84. // self.__WB_MANIFEST is default injection point
  85. // eslint-disable-next-line no-underscore-dangle
  86. precacheAndRoute(self.__WB_MANIFEST);
  87. // clean old assets
  88. cleanupOutdatedCaches();
  89. // to allow work offline
  90. if (import.meta.env.MODE !== "development") {
  91. registerRoute(new NavigationRoute(createHandlerBoundToURL("/")));
  92. registerRoute(({ url }) => url.pathname === "/config.js", new NetworkFirst());
  93. }