sw.js 8.8 KB

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