Yin Cognyto
Yin Cognyto

Reputation: 1136

Remove variables starting with a string from chrome.storage.local in JavaScript

In a chrome extension, I store some variables in chrome.storage.local like this: chrome.storage.local.set({["name" + counter]: ""}, function() {}); (many thanks to Xan's answer regarding ES6 computed property names here), where counter is basically an incremented number.

How can I use chrome.storage.local.remove to remove all the variables starting with "name" that were previously stored, when I don't need them anymore?

Note: I use this type of storage ("name0", "name1", ...) as I can't store them as an array and update it on the fly in chrome.storage.local (I have to first get the array, update it, then store it back, which is unsuitable for large amounts of data). Also, in the case of a new extension execution, I don't know the maximum counter value, so I'm not able to use it within a for loop.

Upvotes: 0

Views: 1496

Answers (1)

Chay22
Chay22

Reputation: 2894

I was trying to put this on a comment since things are outside my capability. But since this gives proper formatting, so.

I looked at chrome.storage that if you pass null to first parameter, you'll get the entire values. So by provide a callback to it, it becomes

chrome.storage.local.get(null, function (items) {
    for (var key in items) {
        if (key.startsWith('name')) { // or key.includes or whatever
            chrome.storage.local.remove(key)
        }
    }
})

Since items stored might big enough, storing keys inside another key name would work perhaps. Example of wrapper functions

function set(key, value) {
    var collectionOfKeys = chrome.storage.local.get('collection_of_keys') || []

    collection_of_keys.push(key)

    chrome.storage.local.set('collection_of_keys', collection_of_keys)
    chrome.storage.local.set('name' + key, value)
}

To remove

chrome.storage.local.remove(chrome.storage.local.get('collection_of_keys'))

Well, dumb enough if the size of keys is still big.

In case you keep it in sequence, maybe track the length of it will do.

function set(key, value) {
    var collectionOfKeyLength = chrome.storage.local.get('collection_of_key_length') || 0

    chrome.storage.local.set('collection_of_key_length', collectionOfKeyLength + 1)
    chrome.storage.local.set('name' + key, value)
}

function remove () {
    for (var i = 0; i < chrome.storage.local.get('collection_of_key_length'); i++) {
        chrome.storage.local.remove('name' + i)
    }
}

Upvotes: 3

Related Questions