5
votes

I'm running a one page landing in HTML5 and i've used bitsofcode's tutorial (https://bitsofco.de/setting-up-a-basic-service-worker/) to implement my first service worker.

Page is set up on one.com and run through cloudflare.

I've added some caching files, but other that that it's intact from source.

Chrome console gives me this error:

Uncaught (in promise) DOMException service-worker.js:1

I know it fires up because before the error I get:

[ServiceWorker] Installed [ServiceWorker] Caching cacheFiles

Looking into the logs i see these messages:

Console: {
  "lineNumber":24,
  "message":"[ServiceWorker] Installed",
  "message_level":1,
  "sourceIdentifier":3,
  "sourceURL":"https://WWW.MYURL.COM/service-worker.js"
}

Console: {
  "lineNumber":33,
  "message":"[ServiceWorker] Caching cacheFiles",
  "message_level":1,
  "sourceIdentifier":3,
  "sourceURL":"https://WWW.MYURL.COM/service-worker.js"
}

Error: {
  "columnNumber":-1,
  "lineNumber":-1,
  "message":"ServiceWorker failed to install: ServiceWorker failed to handle event (event.waitUntil Promise rejected)",
  "sourceURL":""
}

Console: {
  "lineNumber":0,
  "message":"Uncaught (in promise) InvalidStateError: Cache.addAll(): duplicate requests (https://WWW.MYURL.COM/favicon-32x32.png)",
  "message_level":3,
  "sourceIdentifier":1,
  "sourceURL":"https://WWW.MYURL.COM/service-worker.js"
}

Service-worker.js

var cacheName = 'v7'; 

// Default files to always cache
var cacheFiles = [
    './',
    './index.html',
    './favicon-96x96.png',
    './favicon-196x196.png',
    './favicon-128.png',
    './favicon-16x16.png',
    './favicon-32x32.png',
    './favicon-32x32.png',
    './manifest.json',
    './assets/css/images/bg2.jpg',
    './assets/css/images/bg2.webp',
    './assets/css/font-awesome.min.css',
    './assets/fonts/fontawesome-webfont.woff2?v=4.7.0',
    './assets/css/main.css',
    'https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,900'
]


self.addEventListener('install', function(e) {
    console.log('[ServiceWorker] Installed');

    // e.waitUntil Delays the event until the Promise is resolved
    e.waitUntil(

        // Open the cache
        caches.open(cacheName).then(function(cache) {

            // Add all the default files to the cache
            console.log('[ServiceWorker] Caching cacheFiles');
            return cache.addAll(cacheFiles);
        })
    ); // end e.waitUntil
});


self.addEventListener('activate', function(e) {
    console.log('[ServiceWorker] Activated');

    e.waitUntil(

        // Get all the cache keys (cacheName)
        caches.keys().then(function(cacheNames) {
            return Promise.all(cacheNames.map(function(thisCacheName) {

                // If a cached item is saved under a previous cacheName
                if (thisCacheName !== cacheName) {

                    // Delete that cached file
                    console.log('[ServiceWorker] Removing Cached Files from Cache - ', thisCacheName);
                    return caches.delete(thisCacheName);
                }
            }));
        })
    ); // end e.waitUntil

});


self.addEventListener('fetch', function(e) {
    console.log('[ServiceWorker] Fetch', e.request.url);

    // e.respondWidth Responds to the fetch event
    e.respondWith(

        // Check in cache for the request being made
        caches.match(e.request)


            .then(function(response) {

                // If the request is in the cache
                if ( response ) {
                    console.log("[ServiceWorker] Found in Cache", e.request.url, response);
                    // Return the cached version
                    return response;
                }

                // If the request is NOT in the cache, fetch and cache

                var requestClone = e.request.clone();
                fetch(requestClone)
                    .then(function(response) {

                        if ( !response ) {
                            console.log("[ServiceWorker] No response from fetch ")
                            return response;
                        }

                        var responseClone = response.clone();

                        //  Open the cache
                        caches.open(cacheName).then(function(cache) {

                            // Put the fetched response in the cache
                            cache.put(e.request, responseClone);
                            console.log('[ServiceWorker] New Data Cached', e.request.url);

                            // Return the response
                            return response;

                        }); // end caches.open

                    })
                    .catch(function(err) {
                        console.log('[ServiceWorker] Error Fetching & Caching New Data', err);
                    });


            }) // end caches.match(e.request)
    ); // end e.respondWith
});

And registration of the SW (put in last in my html body)

<script type="text/javascript">
        if ('serviceWorker' in navigator) {
          navigator.serviceWorker.register('service-worker.js');
        };      
</script>
1
Please share your service-worker.js and the code that registers your SW. It's hard to help you without those :)pate
@pate updated! :)MaxWillEj

1 Answers

4
votes

You cannot give the same resource to Cache.addAll multiple times.

You have favicon-32x32.png twice. You can also see this from the last console message :)