javascriptclassobjectgoogle-chrome-extensiongoogle-chrome-storage

Does chrome.storage.local delete the class of objects stored in it?


Well I've already asked another question before, but it was the bad question, since I've misinterpreted some things. I've exposed my personnal problem, but someone asked for a reproducible case, which indeed was not simple to set up.

And the reproducible case has indeed the same problem. So, now the reproducible example works, this is just a small chrome extension, with everything that works as intended. Here the .rar for it : Chrome Storage Anomaly (feel free to edit it to find more answer if needed I guess)

You load the extension etc, ain't learning you how that works. After you got 4 buttons, first just load some data in the class/arrays, and show some functions outputs.

Second one on the left of the first show some console.log useful data (but won't work if you didn't use the first button, simply cuz else he read non-existant data).

Third and Fourth (below the two firsts) are pretty simple as written on them you basically SET and GET the variable which has the Garage class, from the chrome.storage.local. And after you created the data with the first button, SET it with the third, and GET it with the fourth, you'll see that first the first button doesn't work cuz the methods/function are not recognized, and secondly with the console.logs button that the two classes disappeared, and are now simple objects.

So tbh the orignal question already has an answer, it seems that yeah it does that, it does erase the original class of the objects you put in it. So my real question is : How do we avoid that ? Or what mistake I've made to end up it doing that ?


Solution

  • We can read here what set accepts as an item

    An object which gives each key/value pair to update storage with. Any other key/value pairs in storage will not be affected. 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).

    It's not directly stated, but considering that functions and nested keys are removed, it won't preserve the class of the object.

    It's hard to serialize the prototype chain in JavaScript and I doubt any library can do this.

    You have to create a new class object every time you get data out of this storage.