Gordon Williams
Gordon Williams

Reputation: 1886

Debugging service worker 'trying to install' in Chrome

I have what I assumed was a pretty standard service worker at http://www.espruino.com/ide/serviceworker.js for the page http://www.espruino.com/ide

However recently, when I have "Update on reload" set in the Chrome dev console for Service Workers the website stays with its loading indicator on, and the status shows a new service worker is "Trying to Install".

Eventually I see a red 'x' by the new service worker and a '1' with a link, but that doesn't do anything or provide any tooltip. Clicking on serviceworker.js brings me to the source file with the first line highlighted in yellow, but there are no errors highlighted.

I've done the usual and checked that all files referenced by the service worker exist and they do, and I have no idea what to look at next.

Does anyone have any clues how to debug this further?

thanks!

Upvotes: 4

Views: 6419

Answers (2)

Terren
Terren

Reputation: 1477

For those running in to this issue with the latest version of Chrome, I was able to fix it by caching each resource in its own cache. Just call caches.open for every file you want to store. You can do this because caches.match will automatically find the file in your sea of caches.

As a messy example:

self.addEventListener('install', event => {
 event.waitUntil(swpromise);
 var swpromise = new Promise(function(resolve,reject) {

 for (var i = 0; i < resources_array.length; i++) {
   addToCache(i,resources_array[i]);
 }

 function addToCache(index,url) {
   caches.open(version+"-"+index).then(cache => cache.addAll([url])).then(function() {cacheDone()});
 }

 var havedone = 0;
 function cacheDone() {
  havedone++;
  if (havedone == resources_array.length) {
   resolve();
  }
 }
})

I used the version number and the index of the file as the cache key for each file. I then delete all of the old caches on activation of the service worker with something similar to the following code:

addEventListener('activate', e => {
 e.waitUntil(caches.keys().then(keys => {
  return Promise.all(keys.map(key => {
    if (key.indexOf(version+"-") == -1) return caches.delete(key);
  }));
 }));
});

Hopefully this works for you, it did in my case.

Upvotes: 0

Gordon Williams
Gordon Williams

Reputation: 1886

I'm on Chrome Beta.

I updated to the newest release a magically everything works. So I guess it was a bug in Chrome or the devtools, not my code.

Upvotes: 0

Related Questions