0

我使用以下代码在 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);

        });

    });  
}

当我运行此方法时,第一个警报显示:GET:old=undefined,第二个警报显示:SET:true就像预期的那样。但是,当使用相同的参数再次调用该方法时,第一个警报 AGAIN 会显示GET:old=undefined,而不是GET:old=true我预期的。

当我使用 storage.local 而不是 storage.sync 时,这是相同的行为

“存储”在清单的权限中。JS是从我的扩展的选项页面调用的-

4

1 回答 1

2

你在做.get("plus1", ...),然后在做.set({"propertyName": newValue}, ...)。您存储在密钥“ propertyName”下,但获取plus1从未设置过的密钥“”。

也许您的误解是对象文字中的键本身就是文字(即使没有引用),而不是变量标识符。在这种情况下,您可能会从阅读How to use chrome.storage in a chrome extension using a variable's value as key name 中受益?.

于 2013-12-02T21:13:29.320 回答