4

I am using workbox in my project but the problem is not specific to workbox.

Can anyone tell me how to retrieve list of all urls from specific cache and return it to callback function. I am trying to show users list of all cached urls and an option to delete them. But i am not able to populate/show list of all cached urls.

What i am doing is:

function queryCache(){
    var url = [];
    caches.open('mycache').then(function (cache){
        cache.keys().then(function(keys){
            return new Promise(function(resolve, reject) {
                keys.forEach(function (request, index, array) {
                    cache.match(request).then(function (response){
                        url.push(response.url);
                    })
                })
                resolve();
            });
        }).then(function(){
            console.log(url); // lists all urls in console as array
            cacheList(url);
        });
    })
}

function cacheList(Items)
{   for(var i = 0; i < Items.length; i++){
        console.log('Items: '+Items[i]); //never reaches
    }
    console.log(Items.length); // always show 0
}

when i call queryCache() from console, cacheList(Items) is called properly but the problem is, Items is always a empty array and its length is always 0.

Probably i am not using Promise resolve properly. Please help Thank you

2 Answers 2

5

I was passing incorrect promise, following is the working code,

There is no such question on stackoverflow or in the web to list all urls of certain cache and pass to an function, I hope It'll help someone.

function queryCache(){
    var url = [];
    caches.open('mycache').then(function (cache){
        cache.keys().then(function(keys){
            return Promise.all(
                    keys.map(function(k){url.push(k.url); return k.url} )
                )
        }).then(function(u){ cacheList(url);})
    })
}

function cacheList(Items)
{   for(var i = 0; i < Items.length; i++){
        console.log('Items: '+Items[i]);
    }
}
1
  • This was really useful in Safari, where the debug tools don't seem to provide any way to list these caches! Thanks! Commented Jun 28, 2022 at 20:45
1
async function getCachedUrls(cacheName, cb) {
  const urls = (await (await caches.open(cacheName)).keys()).map(i => i.url)
  return (cb) ? cb(urls) : urls 
}

getCachedUrls('mycache-v1').then((d) => { console.log(d) })
  // or
getCachedUrls('mycache-v1', console.log)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.