Подтвердить что ты не робот

Храните массив с chrome.storage.local

Я пишу расширение 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}?

4b9b3361

Ответ 1

Я думаю, вы ошиблись 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)
        });
    });
});