Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

javascript - Store an array with chrome.storage.local

I'm writing a chrome extension, and I can't store an array. I read that I should use JSON stringify/parse to achieve this, but I have an error using it.

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)});
        }
    });
});

How could I store an array of objects like {keyPairId: keyPairId,HasBeenUploadedYet: false} ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you've mistaken localStorage for the new Chrome Storage API.
- You needed JSON strings in case of the localStorage
- You can store objects/arrays directly with the new 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)
        });
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...