Store an array with chrome.storage.local

前端 未结 1 1578
执笔经年
执笔经年 2020-12-04 18:05

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.

c         


        
相关标签:
1条回答
  • 2020-12-04 18:44

    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)
            });
        });
    });
    
    0 讨论(0)
提交回复
热议问题