sw.js 9.3 KB

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