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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With