I have a PWA, which has a manifest.json
with a start_url
.
I have a service worker with a fetch
event that only caches certain requests.
This is done in the service worker by overriding the response to proxy from the cache (TypeScript for clarity):
self.addEventListener('fetch', (event: FetchEvent) => {
// This MUST be synchronous until respondWith is called
const cache = isCachable(event.request);
if (!isCachable)
return; // Don't proxy, let the network request continue
// Kick off a promise to check the cache, and clone/cache the response otherwise
const proxy: Promise<Response> = cacheResponse(event);
event.respondWith(proxy);
}
I want to cache the start_url
, which means isCachable
above needs to be able to tell that the value of start_url
is the relative route being requested.
I can load the manifest.json
in the SW but that feels really clunky. I can hard code the values in the SW, but then I need to update two places if config changes.
In the fetch
handler event.request.url
is absolute, but the start_url
is relative to the manifest.json
- so, for instance, I might have:
manifest.json
:{ "start_url": "appshell" ... }
- Web site gets deployed to
www.example.com/folder/
(but might be deployed tosub.example.com
orwww.example.com/a/b
or whatever) - Online user visits site, either visits everything or install script caches direct.
- Later, same user visits offline.
- The fetch above fires with
event.request.url === 'www.example.com/folder/appshell'
- I need the
isCachable
function to be able to tell that resource should be cached synchronously. It needs to determine thatwww.example.com/folder/appshell
isappshell
(resolve the relative link) and thatappshell
is set asstart_url
(read the manifest).
Obviously, all this can be hard coded. However, every PWA needs respond from the cache for start_url
, so this can't be a new problem. Before I reinvent the wheel is there a better way or something I'm missing?
So...
- Given that service workers need the manifest, is there a good way to get the manifest's config in the worker?
- Is there a way to resolve the relative link for comparison with the manifest?
manifest.json
that applies to service workers. Yes this is a progressive web app and not a browser extension. Thestart_url
is relative to the manifest. Theevent.request.url
passed to thefetch
handler in the service worker is absolute, the cache in a service worker is relative to the service worker. I don't need to figure out relative links anywhere else, this question is just about the specific case of the start URL, which needs to be cached by the service worker. – Keith