sw.js 8.5 KB

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