sw.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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 { dbAsync } from "../src/app/db";
  6. import { toNotificationParams, icon, badge } from "../src/app/notificationUtils";
  7. import i18n from "../src/app/i18n";
  8. /**
  9. * General docs for service workers and PWAs:
  10. * https://vite-pwa-org.netlify.app/guide/
  11. * https://developer.chrome.com/docs/workbox/
  12. *
  13. * This file uses the (event) => event.waitUntil(<promise>) pattern.
  14. * This is because the event handler itself cannot be async, but
  15. * the service worker needs to stay active while the promise completes.
  16. */
  17. const broadcastChannel = new BroadcastChannel("web-push-broadcast");
  18. const addNotification = async ({ subscriptionId, message }) => {
  19. const db = await dbAsync();
  20. await db.notifications.add({
  21. ...message,
  22. subscriptionId,
  23. // New marker (used for bubble indicator); cannot be boolean; Dexie index limitation
  24. new: 1,
  25. });
  26. await db.subscriptions.update(subscriptionId, {
  27. last: message.id,
  28. });
  29. const badgeCount = await db.notifications.where({ new: 1 }).count();
  30. console.log("[ServiceWorker] Setting new app badge count", { badgeCount });
  31. self.navigator.setAppBadge?.(badgeCount);
  32. };
  33. /**
  34. * Handle a received web push message and show notification.
  35. *
  36. * Since the service worker cannot play a sound, we send a broadcast to the web app, which (if it is running)
  37. * receives the broadcast and plays a sound (see web/src/app/WebPush.js).
  38. */
  39. const handlePushMessage = async (data) => {
  40. const { subscription_id: subscriptionId, message } = data;
  41. broadcastChannel.postMessage(message); // To potentially play sound
  42. await addNotification({ subscriptionId, message });
  43. await self.registration.showNotification(
  44. ...toNotificationParams({
  45. subscriptionId,
  46. message,
  47. defaultTitle: message.topic,
  48. topicRoute: new URL(message.topic, self.location.origin).toString(),
  49. })
  50. );
  51. };
  52. /**
  53. * Handle a received web push subscription expiring.
  54. */
  55. const handlePushSubscriptionExpiring = async (data) => {
  56. await self.registration.showNotification(i18n.t("web_push_subscription_expiring_title"), {
  57. body: i18n.t("web_push_subscription_expiring_body"),
  58. icon,
  59. data,
  60. badge,
  61. });
  62. };
  63. /**
  64. * Handle unknown push message. We can't ignore the push, since
  65. * permission can be revoked by the browser.
  66. */
  67. const handlePushUnknown = async (data) => {
  68. await self.registration.showNotification(i18n.t("web_push_unknown_notification_title"), {
  69. body: i18n.t("web_push_unknown_notification_body"),
  70. icon,
  71. data,
  72. badge,
  73. });
  74. };
  75. /**
  76. * Handle a received web push notification
  77. * @param {object} data see server/types.go, type webPushPayload
  78. */
  79. const handlePush = async (data) => {
  80. if (data.event === "message") {
  81. await handlePushMessage(data);
  82. } else if (data.event === "subscription_expiring") {
  83. await handlePushSubscriptionExpiring(data);
  84. } else {
  85. await handlePushUnknown(data);
  86. }
  87. };
  88. /**
  89. * Handle a user clicking on the displayed notification from `showNotification`.
  90. * This is also called when the user clicks on an action button.
  91. */
  92. const handleClick = async (event) => {
  93. const clients = await self.clients.matchAll({ type: "window" });
  94. const rootUrl = new URL(self.location.origin);
  95. const rootClient = clients.find((client) => client.url === rootUrl.toString());
  96. // perhaps open on another topic
  97. const fallbackClient = clients[0];
  98. if (!event.notification.data?.message) {
  99. // e.g. something other than a message, e.g. a subscription_expiring event
  100. // simply open the web app on the root route (/)
  101. if (rootClient) {
  102. rootClient.focus();
  103. } else if (fallbackClient) {
  104. fallbackClient.focus();
  105. fallbackClient.navigate(rootUrl.toString());
  106. } else {
  107. self.clients.openWindow(rootUrl);
  108. }
  109. event.notification.close();
  110. } else {
  111. const { message, topicRoute } = event.notification.data;
  112. if (event.action) {
  113. const action = event.notification.data.message.actions.find(({ label }) => event.action === label);
  114. if (action.action === "view") {
  115. self.clients.openWindow(action.url);
  116. } else if (action.action === "http") {
  117. try {
  118. const response = await fetch(action.url, {
  119. method: action.method ?? "POST",
  120. headers: action.headers ?? {},
  121. body: action.body,
  122. });
  123. if (!response.ok) {
  124. throw new Error(`HTTP ${response.status} ${response.statusText}`);
  125. }
  126. } catch (e) {
  127. console.error("[ServiceWorker] Error performing http action", e);
  128. self.registration.showNotification(`${i18n.t("notifications_actions_failed_notification")}: ${action.label} (${action.action})`, {
  129. body: e.message,
  130. icon,
  131. badge,
  132. });
  133. }
  134. }
  135. if (action.clear) {
  136. event.notification.close();
  137. }
  138. } else if (message.click) {
  139. self.clients.openWindow(message.click);
  140. event.notification.close();
  141. } else {
  142. // If no action was clicked, and the message doesn't have a click url:
  143. // - first try focus an open tab on the `/:topic` route
  144. // - if not, use an open tab on the root route (`/`) and navigate to the topic
  145. // - if not, use whichever tab we have open and navigate to the topic
  146. // - finally, open a new tab focused on the topic
  147. const topicClient = clients.find((client) => client.url === topicRoute);
  148. if (topicClient) {
  149. topicClient.focus();
  150. } else if (rootClient) {
  151. rootClient.focus();
  152. rootClient.navigate(topicRoute);
  153. } else if (fallbackClient) {
  154. fallbackClient.focus();
  155. fallbackClient.navigate(topicRoute);
  156. } else {
  157. self.clients.openWindow(topicRoute);
  158. }
  159. event.notification.close();
  160. }
  161. }
  162. };
  163. self.addEventListener("install", () => {
  164. console.log("[ServiceWorker] Installed");
  165. self.skipWaiting();
  166. });
  167. self.addEventListener("activate", () => {
  168. console.log("[ServiceWorker] Activated");
  169. self.skipWaiting();
  170. });
  171. // There's no good way to test this, and Chrome doesn't seem to implement this,
  172. // so leaving it for now
  173. self.addEventListener("pushsubscriptionchange", (event) => {
  174. console.log("[ServiceWorker] PushSubscriptionChange");
  175. console.log(event);
  176. });
  177. self.addEventListener("push", (event) => {
  178. const data = event.data.json();
  179. console.log("[ServiceWorker] Received Web Push Event", { event, data });
  180. event.waitUntil(handlePush(data));
  181. });
  182. self.addEventListener("notificationclick", (event) => {
  183. console.log("[ServiceWorker] NotificationClick");
  184. event.waitUntil(handleClick(event));
  185. });
  186. // See https://vite-pwa-org.netlify.app/guide/inject-manifest.html#service-worker-code
  187. // self.__WB_MANIFEST is the workbox injection point that injects the manifest of the
  188. // vite dist files and their revision ids, for example:
  189. // [{"revision":"aaabbbcccdddeeefff12345","url":"/index.html"},...]
  190. precacheAndRoute(
  191. // eslint-disable-next-line no-underscore-dangle
  192. self.__WB_MANIFEST
  193. );
  194. // Delete any cached old dist files from previous service worker versions
  195. cleanupOutdatedCaches();
  196. if (import.meta.env.MODE !== "development") {
  197. // since the manifest only includes `/index.html`, this manually adds the root route `/`
  198. registerRoute(new NavigationRoute(createHandlerBoundToURL("/")));
  199. // the manifest excludes config.js (see vite.config.js) since the dist-file differs from the
  200. // actual config served by the go server. this adds it back with `NetworkFirst`, so that the
  201. // most recent config from the go server is cached, but the app still works if the network
  202. // is unavailable. this is important since there's no "refresh" button in the installed pwa
  203. // to force a reload.
  204. registerRoute(({ url }) => url.pathname === "/config.js", new NetworkFirst());
  205. }