sw.js 8.7 KB

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