How to download all files with the service worker in a progressive web-app for offline-use?

2.9k Views Asked by At

I have a problem with Progressive Web Apps. I have an app and the service worker is registered successfully. I can download the app. However, only the index.html works offline and not all other subpages. However, I have added them in the array to save. On Windows it works fine. Only on the smartphone it does not. My default browser is the Samsung browser (Samsung smartphone) What can I do? Do you have any ideas?

Here is my registration in the index.hmtl:

if ("serviceWorker" in navigator) {
     window.addEventListener('load', function() {
      navigator.serviceWorker.register( "./SW.js").then(
       function(erfolg) {
        console.log( "ServiceWorker wurde registriert.", erfolg);
       }
      ).catch(
       function(fehler) {
        console.log( "ServiceWorker wurde leider nicht registriert.", fehler);
       }
      );
     });
    }

Here is my SW.js with the events for the service worker:

const contentToCache = [
  '/index.html',
  '/Upload.html',
  '/Save.html',
  '/Routing.js',
  '/LocalStorageService.js'
];

self.addEventListener('install', (e) => {
console.log("[SERVICE WORKER] INSTALL DATA");
e.waitUntil((async () => {
  const cache = await caches.open("Baum-App");
  await cache.addAll(contentToCache);
})());
});

self.addEventListener('fetch', (e) => {
  e.respondWith((async () => {
    const r = await caches.match(e.request);
    console.log(`[Service Worker] Fetching resource: ${e.request.url}`);
    if (r) { return r; }
    const response = await fetch(e.request);
    const cache = await caches.open("Baum-App");
    console.log(`[Service Worker] Caching new resource: ${e.request.url}`);
    cache.put(e.request, response.clone());
    return response;
  })());
});

I ran the app on Windows and it works there. I have tried a lot, but unfortunately I don't know much about it yet.

2

There are 2 best solutions below

0
On

I ran into this issue also. I fixed it by insuring that the strings used in the array of contentToCache matches the case of each character used in the file names (on physical disk).

In other words; the desktop browser does not distinguish between Upload.html and upload.html, but the browser on your mobile device does! (This is especially true for the Windows Operating System)

For the Linux operating system on the other hand, it is case-sensitive. So if you are targeting android devices, you need to keep this in mind.

0
On

Unfortunately, I think third-party browsers have limited support (e.g. Safari, Samsung, etc.). There probably exists a workaround somewhere, but I'd honestly just go with a regex check on navigator.userAgent and then just show a little toast message for any browser other than Chrome/Firefox (maybe even Edge at this point).