Cannot save in chrome Storage

628 views Asked by At

I use the following code to load and save a value in chrome.storage:

$(document).ready(function() 
{
    $( "#filterPlus" ).click(function() 
    {
        SaveSwitch("plus1","#filterPlus","plus1");
    });
}
function SaveSwitch(propertyName, imageId, imageSrc) 
{
    chrome.storage.sync.get(propertyName, function (result) {
        var oldValue = result.propertyName;
        alert('GET:old='+oldValue);  
        if (oldValue==null) 
        {
            oldValue=false;
        }
        var newValue=!oldValue;

        chrome.storage.sync.set({propertyName: newValue}, function() 
        {
            alert('SET:'+newValue);

        });

    });  
}

When I run through this method, the first alert shows:GET:old=undefined, the second alert shows:SET:true just like expected. But when calling that method again with the same parameters the first alert AGAIN shows GET:old=undefined instead of GET:old=true which I expected.

It is the same behaviour when I use storage.local instead of storage.sync

"storage" is in the manifest's permissions. The JS is called from the options-page of my extension-

1

There are 1 answers

0
apsillers On BEST ANSWER

You're doing .get("plus1", ...) and then later doing .set({"propertyName": newValue}, ...). You are storing under the key "propertyName" but fetching the key "plus1", which has never been set.

Perhaps your misunderstanding is that keys in object literals are themselves literal (even when not quoted), rather than variable identifiers. In that case, you might benefit form reading How to use chrome.storage in a chrome extension using a variable's value as the key name?.