javascript 使用 chrome.storage.local 存储数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16605706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:18:25  来源:igfitidea点击:

Store an array with chrome.storage.local

javascriptgoogle-chromegoogle-chrome-extensionlocal-storage

提问by little-dude

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 扩展程序,但无法存储数组。我读到我应该使用 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)});
        }
    });
});

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

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

回答by gblazex

I think you've mistaken localStoragefor the new Chrome Storage API.
- You needed JSON strings in case of the localStorage
- You can store objects/arrays directlywith the newStorage API

我想你误认为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)
        });
    });
});