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

泄露秘密 提交于 2020-01-06 07:55:29

问题


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.


回答1:


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)
    }
}


来源:https://stackoverflow.com/questions/47961903/remove-variables-starting-with-a-string-from-chrome-storage-local-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!