I developped a service worker which is serving pages from network first (and caching it) or, when offline, serving it from cache.
Ideally, I would like to inform the user (with a banner, or something like this) that the page has been served from the cache because we detected that he was offline.
Do you have an idea on how to implement this ?
Some ideas I had (but didn't really succeeded to implement) :
- Inject some code in the cached response body (like, injecting some JS code triggering a
offline-detectedevent which may or may not have an event listener on the webpage, depending on if I want to do something or not on this webpage while offline).
=> I didn't found how to append stuff in response's body coming from the cache to do this. - Send a
postMessagefrom service worker to the webpage telling that it has been rendered using a cached content.
=> It doesn't seem to be possible as I don't have anyMessagePortavailable in ServiceWorker'sfetchevent, making it impossible to send anypostMessage()to it.
If you have any idea on how to implement this, I would be very happy to discuss about it.
Thanks in advance :)
I looked at different solutions :
navigator.onLineflag on HTML page : this is not reliable on my case, as my service worker might served cached page (because of, let's say, a timeout) whilst the browser can consider to be onlinepostMessage()few seconds after content is served : problem is, in that case, thatfetchevent on the "starting" HTML page, doesn't have anyclientIdyet (we have a chicken & egg problem here, since service worker is not yet attached to the client at the moment the root html page is served from cache)The only remaining solution I found was to inject some code in the cached response.
Something like this on the service worker side (the main idea is to inject some code on cached response body, triggering a
served-offline-pageevent once DOM content has been loaded) :On the HTML page, this is simple, we only have to write this in the page :