Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 912
Supersharp Avatar asked Jul 24 '15 07:07

Supersharp


2 Answers

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.

like image 82
Xan Avatar answered Oct 10 '22 23:10

Xan


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.

like image 44
smnbbrv Avatar answered Oct 11 '22 00:10

smnbbrv