简体   繁体   中英

How to get a JSON data from chrome storage

I have worked my head off trying different possible solutions for this and nothing works, If I post my different codes that I tried, It causes a lot of confusion, so I kept this question short.

Say I have an object as follows:

object1= ["vlah", "", "", "", "", "marc", "aojesl", "", "", ""]

Converting it to JSON and setting objectA as key for the object1:

chrome.storage.sync.set({'objectA': JSON.stringify(object1)});

How do retrieve or get/parse the JSON object from chrome storage to store its values again in an object?

Using chrome.storage.sync.get you can get the whole storage. The first argument is an array of the keys you are interested in, in your case only 'objectA' . Your second argument is the callback function, that will be called once the value(s) has/have been found. The callback will be called with a result object, which is your storage with only the keys you have specified. Now you can use result.objectA to get your string and JSON.parse() to convert it back to an object.

chrome.storage.sync.get(['objectA'], function(result) {
      const objectA = JSON.parse(result.objectA);
});

Further reading:

https://developer.chrome.com/extensions/storage

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM