]> cat aescling's git repositories - mastodon.git/commitdiff
Cache HTML page with Service Worker (#6802)
authorAkihiko Odaki <akihiko.odaki.4i@stu.hosei.ac.jp>
Sat, 17 Mar 2018 11:35:13 +0000 (20:35 +0900)
committerEugen Rochko <eugen@zeonfederated.com>
Sat, 17 Mar 2018 11:35:13 +0000 (12:35 +0100)
This is the first step to make Mastodon work offline. It is also required
by Chromium to trigger Web Manifest automated install prompt.

app/javascript/mastodon/service_worker/entry.js

index eea4cfc3c2f82b735f2cf6c20e79da0ca1d15afc..ad933b95ee468205ce5eb71fd7dc289f2a4d20ce 100644 (file)
@@ -1,10 +1,30 @@
 import './web_push_notifications';
 
+function fetchRoot() {
+  return fetch('/', { credentials: 'include' });
+}
+
 // Cause a new version of a registered Service Worker to replace an existing one
 // that is already installed, and replace the currently active worker on open pages.
 self.addEventListener('install', function(event) {
-  event.waitUntil(self.skipWaiting());
+  const promises = Promise.all([caches.open('mastodon-web'), fetchRoot()]);
+  const asyncAdd = promises.then(([cache, root]) => cache.put('/', root));
+
+  event.waitUntil(asyncAdd);
 });
 self.addEventListener('activate', function(event) {
   event.waitUntil(self.clients.claim());
 });
+self.addEventListener('fetch', function(event) {
+  const url = new URL(event.request.url);
+
+  if (url.pathname.startsWith('/web/')) {
+    event.respondWith(fetchRoot().then(response => {
+      if (response.ok) {
+        return response;
+      }
+
+      throw null;
+    }).catch(() => caches.match('/')));
+  }
+});