diff options
author | Akihiko Odaki <akihiko.odaki.4i@stu.hosei.ac.jp> | 2018-03-17 20:35:13 +0900 |
---|---|---|
committer | Eugen Rochko <eugen@zeonfederated.com> | 2018-03-17 12:35:13 +0100 |
commit | f0cd957c7a8a53dea2eb08a45578084b4d8bb5b4 (patch) | |
tree | 8970a53f15ece4c18f33b8ab78ac90f29e25df6b | |
parent | 64fc8d2b077c76530f59f4da173659982caa9964 (diff) |
Cache HTML page with Service Worker (#6802)
This is the first step to make Mastodon work offline. It is also required by Chromium to trigger Web Manifest automated install prompt.
-rw-r--r-- | app/javascript/mastodon/service_worker/entry.js | 22 |
1 files changed, 21 insertions, 1 deletions
diff --git a/app/javascript/mastodon/service_worker/entry.js b/app/javascript/mastodon/service_worker/entry.js index eea4cfc3c..ad933b95e 100644 --- a/app/javascript/mastodon/service_worker/entry.js +++ b/app/javascript/mastodon/service_worker/entry.js @@ -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('/'))); + } +}); |