Supersharp
Supersharp

Reputation: 31189

How can I store a Map object in a Chrome App?

Using Chrome API chrome.storage.local, I can save and successfully retreive an array but I cannot retreive a Map object.

var folders = new Map()
//... populate Map
chrome.storage.local.set( { "myFolders": folders } )

chrome.storage.local.get( "myFolders", function ( saved ) 
{
  console.assert( typeof saved.myFolders.size === 'number', "not a Map!" )
} )

I'm forced to convert Map in Array before storing. Could I store Map objects directly ?

Upvotes: 7

Views: 2248

Answers (3)

andrej
andrej

Reputation: 4763

You can't JSON.stringify the Map, so it does not work out of the box as expected. However, the question was "how" so here it is:

var folders = new Map()
//... populate Map

// save
chrome.storage.local.set(
  { "myFolders": Object.fromEntries(folders) }
)

// load
chrome.storage.local.get( "myFolders",
  function(saved){
    folders = new Map(Object.entries(result.myFolders));
    console.log(folders);
  }
)

Please bear in mind the API is asynchronous, so the folders will be loaded ages after the chrome.storage.local.get call ends.

Upvotes: 3

Xan
Xan

Reputation: 77541

No, you can't store, or pass with Messaging, objects that are not JSON-serializable (DOM nodes being another frequent example).

And a Map is not:

> JSON.stringify(new Map().set("a", "b"))
"{}"

So, you can only store what JSON can encode. That means that you'll have to do your own serialization/deserialization on top of storage access.

Edit: as Simon's answer shows, Chrome performs more elaborate serialization than JSON (preserving RegExp and Date), but the principle still stands: non-primitive objects need custom serialization.

Upvotes: 9

smnbbrv
smnbbrv

Reputation: 24561

Well, check the documentation:

Primitive values such as numbers will serialize as expected. Values with a typeof "object" and "function" will typically serialize to {}, with the exception of Array (serializes as expected), Date, and Regex (serialize using their String representation).

So you cannot do that directly without converting the data.

Upvotes: 2

Related Questions