admin管理员组

文章数量:1417031

I have been following this tutorial on Progressive Web Apps and I am trying to find a way to present the user with some sort of message when the app is offline. My code so far is pretty much the same as the tutorial:

var cacheName = 'demoPWA-v1';
var filesToCache = [
    '/',
    '/index.html',
    '/js/app.js',
    '/icons/pwa-256x256.png'
];

self.addEventListener('install', function(e) {
    console.log('[demoPWA - ServiceWorker] Install event fired.');
    e.waitUntil(
        caches.open(cacheName).then(function(cache) {
            console.log('[demoPWA - ServiceWorker] Caching app shell...');
            return cache.addAll(filesToCache);
        })
    );
});

self.addEventListener('activate', function(e) {
    console.log('[demoPWA - ServiceWorker] Activate event fired.');
    e.waitUntil(
        caches.keys().then(function(keyList) {
            return Promise.all(keyList.map(function(key) {
                if (key !== cacheName) {
                    console.log('[demoPWA - ServiceWorker] Removing old cache...', key);
                    return caches.delete(key);
                }
            }));
        })
    );
    return self.clients.claim();
});

self.addEventListener('fetch', function(e) {
    console.log('[demoPWA - ServiceWorker] Fetch event fired.', e.request.url);
    e.respondWith(
        caches.match(e.request).then(function(response) {
            if (response) {
                console.log('[demoPWA - ServiceWorker] Retrieving from cache...');
                return response;
            }
            console.log('[demoPWA - ServiceWorker] Retrieving from URL...');
            return fetch(e.request);
        })
    );
});

When I check the Offline checkbox in Chrome under Application > Service Workers, I get a couple of errors, like you can see below:

I wonder if there is some way to deal with this errors and, while doing so, show a message of some sort to the user, informing them of the fact that they are offline.

I have been following this tutorial on Progressive Web Apps and I am trying to find a way to present the user with some sort of message when the app is offline. My code so far is pretty much the same as the tutorial:

var cacheName = 'demoPWA-v1';
var filesToCache = [
    '/',
    '/index.html',
    '/js/app.js',
    '/icons/pwa-256x256.png'
];

self.addEventListener('install', function(e) {
    console.log('[demoPWA - ServiceWorker] Install event fired.');
    e.waitUntil(
        caches.open(cacheName).then(function(cache) {
            console.log('[demoPWA - ServiceWorker] Caching app shell...');
            return cache.addAll(filesToCache);
        })
    );
});

self.addEventListener('activate', function(e) {
    console.log('[demoPWA - ServiceWorker] Activate event fired.');
    e.waitUntil(
        caches.keys().then(function(keyList) {
            return Promise.all(keyList.map(function(key) {
                if (key !== cacheName) {
                    console.log('[demoPWA - ServiceWorker] Removing old cache...', key);
                    return caches.delete(key);
                }
            }));
        })
    );
    return self.clients.claim();
});

self.addEventListener('fetch', function(e) {
    console.log('[demoPWA - ServiceWorker] Fetch event fired.', e.request.url);
    e.respondWith(
        caches.match(e.request).then(function(response) {
            if (response) {
                console.log('[demoPWA - ServiceWorker] Retrieving from cache...');
                return response;
            }
            console.log('[demoPWA - ServiceWorker] Retrieving from URL...');
            return fetch(e.request);
        })
    );
});

When I check the Offline checkbox in Chrome under Application > Service Workers, I get a couple of errors, like you can see below:

I wonder if there is some way to deal with this errors and, while doing so, show a message of some sort to the user, informing them of the fact that they are offline.

Share Improve this question edited Feb 9, 2017 at 23:53 Angelos Chalaris asked Feb 9, 2017 at 23:41 Angelos ChalarisAngelos Chalaris 6,7278 gold badges53 silver badges81 bronze badges 4
  • fetch, returns a promise. so you can just catch the error.. fetch(e.request).catch(function (e) { (*do your stuff*)} – Keith Commented Feb 9, 2017 at 23:44
  • @Keith could you post an answer based on that logic? Maybe explain in more detail, if you can. – Angelos Chalaris Commented Feb 9, 2017 at 23:46
  • Can do, but what way would you inform the user?.. The simplest would be just use alert, will that do for now for example? – Keith Commented Feb 9, 2017 at 23:48
  • @Keith I would like to write the message to some HTML element, but alert will do in order to showcase the solution! – Angelos Chalaris Commented Feb 9, 2017 at 23:49
Add a ment  | 

2 Answers 2

Reset to default 3

Below is the mods just to do an alert, you can then change the alert to say using Jquery or direct DOM to update your HTML page..

self.addEventListener('fetch', function(e) {
    console.log('[demoPWA - ServiceWorker] Fetch event fired.', e.request.url);
    e.respondWith(
        caches.match(e.request).then(function(response) {
            if (response) {
                console.log('[demoPWA - ServiceWorker] Retrieving from cache...');
                return response;
            }
            console.log('[demoPWA - ServiceWorker] Retrieving from URL...');
            return fetch(e.request).catch(function (e) {
               //you might want to do more error checking here too,
               //eg, check what e is returning..
               alert('You appear to be offline, please try again when back online');
            });
        })
    );
});

Yes, what you are doing, it makes perfect sense, as long as you are sure that the cache is not empty, since you only intend to use it to display an offline warning.

The MDN code is really problematic and catch() is not working, I made some modifications and it worked, as for catch(), I haven't had time to solve the problem yet, if you find the solution first, let me know! Here's the code:

var CACHE_VERSION = 1;

// Smallest identifier for a specific version of the cache
var CURRENT_CACHES = {
  font: 'OFFLINE_CACHE' + CACHE_VERSION
};

self.addEventListener('fetch', function(event) {
 // console.log(event);
// We only want to call event.respondWith() if this is a GET request for an HTML document.
  if (event.request.method === 'GET') {
    console.log('Handling fetch event for', event.request.url);

  event.respondWith(

    // Opens the cache object that starts with 'font'
    caches.open(CURRENT_CACHES['font']).then(function(cache) {
      return cache.match(event.request).then(function(response) {
        if (response) {
          console.log('Found cached answer:', response);
          return response;
        } else {
        //Did not find answer in cache
        return fetch(event.request).then(function(fetchresponse) {
        console.log("Request Result - redirected:" + fetchresponse.redirected + ", status:" + fetchresponse.status + ", statusText:" + fetchresponse.statusText + ", type:" + fetchresponse.type + ", url:" + fetchresponse.url);
        if(fetchresponse.status == '200' || fetchresponse.status == '201' || fetchresponse.status == '202' || fetchresponse.status == '203' || fetchresponse.status == '204' || fetchresponse.status == '206'){
               return fetchresponse;    
         } else {
         console.log('The request returned http code 30*, 40* or 50*.');
         return false;
         }    
        }).catch(function(e) {
         //Offline version
        return new Response('<html><title></title><strong>Sorry, You are offline!</strong></html>', {"status" : 202, "headers" : {"Content-Type" : "text/html; charset=utf-8"}});
        });
        }
      }).catch(function(error) {
        //This .catch () doesn't seem to work, as I said, but it won't give you any problems, it just takes up space.

        // Handles exceptions that e from match () or fetch ().

        console.error('  Error:', error);

        throw error;
      });
    })
  );
  };
});

本文标签: javascriptHandling fetch requests in Progressive Web App when offlineStack Overflow