Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store an array with chrome.storage.local

Tags:

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} ?

like image 567
little-dude Avatar asked May 17 '13 09:05

little-dude


People also ask

Can you store arrays in Chrome storage?

You can store arrays directly.

Can local storage store array?

The array becomes a string and you can save it into your browser's local storage.

How do I save an array of objects to local storage?

To save arrays or objects using the localStorage API in JavaScript, we need to first stringify the arrays or objects using the JSON. stringify() method, and when we need to retrieve the value we can use the JSON. parse() method.

Does Chrome support local storage?

Google Chrome/ChromiumChrome treats cookies and local storage as the same thing, so these steps work for both. Click on the menu button in the top-right corner of your Chrome window. Select “Settings” from that menu. Click “Cookies and site permissions”.


1 Answers

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)         });     }); }); 
like image 179
25 revs, 4 users 83% Avatar answered Sep 19 '22 15:09

25 revs, 4 users 83%