Home > OS >  Can't add requests to CacheStorage under the message event of serviceWorker
Can't add requests to CacheStorage under the message event of serviceWorker

Time:12-19

I'm trying to pass an array of urls to serviceWorker so that the latter can add them to CacheStorage:

main.js:

let arr = ['/image1.jpg', '/image2.jpg'];
navigator.serviceWorker.register('/serviceWorker.js');
navigator.serviceWorker.ready.then(registration => {
    registration.active.postMessage(arr);
});

serviceWorker.js:

self.addEventListener('message', function (e) {
    console.log(e.data);
    caches.open('my_cache_name').then(function(cache) {
        return cache.addAll(e.data);
    });
});

But I receive the error

Failed to execute 'addAll' on 'Cache': Request failed

At that I successfully receive the array in the console.log()

CodePudding user response:

I think the problem might be from addressing files

sth that you are trying to add into cache storage (using addAll) is file names, so cacheStorage will try to find those files and store them and if it can't find or face 404 it will return this error

forexample if your array is ['styles.css',...] cacheStorage will try to find styles.css and others and store them

if you want to save text or sth different from files in cache it would be better to store them in indexDB instead

  • Related