javascriptgoogle-chromegoogle-chrome-extension

chrome extension chrome.storage how to do a lot of get and set the same time and avoid race condition?


I get an object from chrome.storage.local.get and then I want to update that object by using chrome.storage.local.set in the callback.

If the callback is executed multiple times a race condition happens. What can I do to avoid this?

I know it can be resolved by jQuery.defer, but is there any method to do an atomic update? Or any suggestions to improve my code?

Below is a very simple example:

chrome.tabs.onCreated.addListener(function(tab){//a lot of at the same time
    //just test
    chrome.storage.local.get(null, function(items) {
            if(!items.test){
                items.test=[];
            }
            items.test.push(something);
            chrome.storage.local.set(items,function(){});
            console.log('a'+JSON.stringify(items));
        });    
});

Solution


One solution is to use localStorage in combination with chrome.storage.

You can use localStorage for all the frequent get and set from your listener. Setting and getting localStorage is synchronous/blocking so there is no need to worry about race conditions.

You can then decide some idle time/event to sync localStorage with chrome.storage.

This would work assuming that the user will be using this extension at one computer at any one time.