sw.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. Chatspace - service worker (PWA)
  3. Network-first with a cached fallback for the static app shell, so the
  4. installed app opens instantly and survives brief connectivity drops.
  5. Everything dynamic (the /system/ API surface, WebSockets, uploads and
  6. downloads) is deliberately left to the network - chat data must never
  7. be served stale from a cache.
  8. */
  9. var CACHE_NAME = "chatspace-shell-v2";
  10. var SHELL_ASSETS = [
  11. "index.html",
  12. "app.css",
  13. "app.js",
  14. "manifest.json",
  15. "img/module_icon.svg",
  16. "img/logo192.png",
  17. "img/logo512.png",
  18. "../script/semantic/semantic.min.css",
  19. "../script/jquery.min.js",
  20. "../script/ao_module.js"
  21. ];
  22. self.addEventListener("install", function (event) {
  23. event.waitUntil(
  24. caches.open(CACHE_NAME).then(function (cache) {
  25. //Best effort: a missing optional asset must not fail the install
  26. return Promise.all(SHELL_ASSETS.map(function (asset) {
  27. return cache.add(asset).catch(function () { });
  28. }));
  29. }).then(function () {
  30. return self.skipWaiting();
  31. })
  32. );
  33. });
  34. self.addEventListener("activate", function (event) {
  35. event.waitUntil(
  36. caches.keys().then(function (names) {
  37. return Promise.all(names.map(function (name) {
  38. if (name !== CACHE_NAME) return caches.delete(name);
  39. }));
  40. }).then(function () {
  41. return self.clients.claim();
  42. })
  43. );
  44. });
  45. self.addEventListener("fetch", function (event) {
  46. var req = event.request;
  47. if (req.method !== "GET") return;
  48. //Never intercept the live API / auth / media surface
  49. if (req.url.indexOf("/system/") >= 0 || req.url.indexOf("/api/") >= 0) return;
  50. event.respondWith(
  51. fetch(req).then(function (resp) {
  52. //Refresh the shell copy on every successful fetch
  53. if (resp && resp.ok && req.url.indexOf(self.location.origin) === 0) {
  54. var copy = resp.clone();
  55. caches.open(CACHE_NAME).then(function (cache) {
  56. cache.put(req, copy).catch(function () { });
  57. }).catch(function () { });
  58. }
  59. return resp;
  60. }).catch(function () {
  61. return caches.match(req).then(function (hit) {
  62. return hit || Response.error();
  63. });
  64. })
  65. );
  66. });