24

我正在编写一个 chrome 扩展,但我无法存储数组。我读到我应该使用 JSON stringify/parse 来实现这一点,但使用它时出错。

chrome.storage.local.get(null, function(userKeyIds){
    if(userKeyIds===null){
        userKeyIds = [];
    }
    var userKeyIdsArray = JSON.parse(userKeyIds);
    // Here I have an Uncaught SyntaxError: Unexpected token o
    userKeyIdsArray.push({keyPairId: keyPairId,HasBeenUploadedYet: false});
    chrome.storage.local.set(JSON.stringify(userKeyIdsArray),function(){
        if(chrome.runtime.lastError){
            console.log("An error occured : "+chrome.runtime.lastError);
        }
        else{
            chrome.storage.local.get(null, function(userKeyIds){
                console.log(userKeyIds)});
        }
    });
});

我如何存储像 {keyPairId: keyPairId,HasBeenUploadedYet: false} 这样的对象数组?

4

1 回答 1

48

我认为您误认为localStorage新的 Chrome 了Storage API
- 在这种情况下,您需要 JSON 字符串- 您可以使用新的直接localStorage
存储对象/数组 Storage API

// by passing an object you can define default values e.g.: []
chrome.storage.local.get({userKeyIds: []}, function (result) {
    // the input argument is ALWAYS an object containing the queried keys
    // so we select the key we need
    var userKeyIds = result.userKeyIds;
    userKeyIds.push({keyPairId: keyPairId, HasBeenUploadedYet: false});
    // set the new array value to the same key
    chrome.storage.local.set({userKeyIds: userKeyIds}, function () {
        // you can use strings instead of objects
        // if you don't  want to define default values
        chrome.storage.local.get('userKeyIds', function (result) {
            console.log(result.userKeyIds)
        });
    });
});
于 2013-05-18T13:34:51.850 回答