【问题标题】:Cannot save in chrome Storage无法保存在 chrome 存储中
【发布时间】:2013-12-03 05:13:29
【问题描述】:

我使用以下代码在 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 时,这是相同的行为

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

【问题讨论】:

    标签: google-chrome-extension google-chrome-storage


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      • 2016-04-29
      • 2012-02-12
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多