PWA How to notify the user that he is offline

I am using the ionic PWA Service worker. I got it to work nicely with one caveat. I can’t figure out how to notify the user that they are using an offline version and that the data may be stale

I found this post here: which shows how to catch instances when the user is offline and to show him an offline page. I tried to produce something similar with the following code

self.toolbox.router.get('/(.*)', function(req, vals, opts) {
  return toolbox.networkFirst(req, vals, opts)
    .catch(function(error) {
      if (req.method === 'GET' && req.headers.get('accept').includes('text/html')) {
        return toolbox.cacheOnly(new Request('/#/offline'), vals, opts);
      throw error;

which didn’t work. I also tried:

var url = req.url.replace(/#.*/, '#/offline');
return toolbox.cacheOnly(new Request(url), vals, opts);

which also didn’t work. I don’t need a seperate page I just want to be able to show the user an ionic popup saying that he is offline. Any help is greatly appreciated.

Simplest thought that comes to mind is just attempt to git your server on start, and give it a short timeout. If it falls show the error

Ya I thought about doing that, but I’d rather not if there is a better way. I will probably do that if I can’t find something better

Not sure how one would achieve what you want from within service worker. But in my app I did state detection using Josh’s approach here: works fine.

That’s an app not a pwa, you can’t do that in a pwa

Yes, but the code there contains conditions for a web app - via navigator.isOnline. I may have linked wrong artile though:slight_smile:

Here is the snippet I use:

this.browserOffline = Observable.fromEvent(window, 'offline').subscribe(() => {
        this.appIsOnline = false;
this.browserOnline = Observable.fromEvent(window, 'online').subscribe(() => {
        this.appIsOnline = true;
1 Like

You are correct, sorry, I missed that! I just saw the main point about using the Network plugin, I should have read it more thoroughly before commenting!

no worries;)

on the topic - I think still the problem for online/offline detection is a tough one since there is no one cross browser interface to do such detection. In y case I try to focus specific browsers and not to promise users that it will work across the board.