sw.js 8.6 KB

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