service-worker.js 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // This service worker is required to expose an exported Godot project as a
  2. // Progressive Web App. It provides an offline fallback page telling the user
  3. // that they need an Internet connection to run the project if desired.
  4. // Incrementing CACHE_VERSION will kick off the install event and force
  5. // previously cached resources to be updated from the network.
  6. const CACHE_VERSION = "@GODOT_VERSION@";
  7. const CACHE_PREFIX = "@GODOT_NAME@-sw-cache-";
  8. const CACHE_NAME = CACHE_PREFIX + CACHE_VERSION;
  9. const OFFLINE_URL = "@GODOT_OFFLINE_PAGE@";
  10. // Files that will be cached on load.
  11. const CACHED_FILES = @GODOT_CACHE@;
  12. // Files that we might not want the user to preload, and will only be cached on first load.
  13. const CACHABLE_FILES = @GODOT_OPT_CACHE@;
  14. const FULL_CACHE = CACHED_FILES.concat(CACHABLE_FILES);
  15. self.addEventListener("install", (event) => {
  16. event.waitUntil(caches.open(CACHE_NAME).then(cache => cache.addAll(CACHED_FILES)));
  17. });
  18. self.addEventListener("activate", (event) => {
  19. event.waitUntil(caches.keys().then(
  20. function (keys) {
  21. // Remove old caches.
  22. return Promise.all(keys.filter(key => key.startsWith(CACHE_PREFIX) && key != CACHE_NAME).map(key => caches.delete(key)));
  23. }).then(function() {
  24. // Enable navigation preload if available.
  25. return ("navigationPreload" in self.registration) ? self.registration.navigationPreload.enable() : Promise.resolve();
  26. })
  27. );
  28. });
  29. async function fetchAndCache(event, cache, isCachable) {
  30. // Use the preloaded response, if it's there
  31. let response = await event.preloadResponse;
  32. if (!response) {
  33. // Or, go over network.
  34. response = await self.fetch(event.request);
  35. }
  36. if (isCachable) {
  37. // And update the cache
  38. cache.put(event.request, response.clone());
  39. }
  40. return response;
  41. }
  42. self.addEventListener("fetch", (event) => {
  43. const isNavigate = event.request.mode === "navigate";
  44. const url = event.request.url || "";
  45. const referrer = event.request.referrer || "";
  46. const base = referrer.slice(0, referrer.lastIndexOf("/") + 1);
  47. const local = url.startsWith(base) ? url.replace(base, "") : "";
  48. const isCachable = FULL_CACHE.some(v => v === local) || (base === referrer && base.endsWith(CACHED_FILES[0]));
  49. if (isNavigate || isCachable) {
  50. event.respondWith(async function () {
  51. // Try to use cache first
  52. const cache = await caches.open(CACHE_NAME);
  53. if (event.request.mode === "navigate") {
  54. // Check if we have full cache during HTML page request.
  55. const fullCache = await Promise.all(FULL_CACHE.map(name => cache.match(name)));
  56. const missing = fullCache.some(v => v === undefined);
  57. if (missing) {
  58. try {
  59. // Try network if some cached file is missing (so we can display offline page in case).
  60. return await fetchAndCache(event, cache, isCachable);
  61. } catch (e) {
  62. // And return the hopefully always cached offline page in case of network failure.
  63. console.error("Network error: ", e);
  64. return await caches.match(OFFLINE_URL);
  65. }
  66. }
  67. }
  68. const cached = await cache.match(event.request);
  69. if (cached) {
  70. return cached;
  71. } else {
  72. // Try network if don't have it in cache.
  73. return await fetchAndCache(event, cache, isCachable);
  74. }
  75. }());
  76. }
  77. });
  78. self.addEventListener("message", (event) => {
  79. // No cross origin
  80. if (event.origin != self.origin) {
  81. return;
  82. }
  83. const id = event.source.id || "";
  84. const msg = event.data || "";
  85. // Ensure it's one of our clients.
  86. self.clients.get(id).then(function (client) {
  87. if (!client) {
  88. return; // Not a valid client.
  89. }
  90. if (msg === "claim") {
  91. self.skipWaiting().then(() => self.clients.claim());
  92. } else if (msg === "clear") {
  93. caches.delete(CACHE_NAME);
  94. } else if (msg === "update") {
  95. self.skipWaiting().then(() => self.clients.claim()).then(() => self.clients.matchAll()).then(all => all.forEach(c => c.navigate(c.url)));
  96. } else {
  97. onClientMessage(event);
  98. }
  99. });
  100. });