Note that there are some explanatory texts on larger screens.

plurals
  1. POStoring Objects in HTML5 localStorage
    text
    copied!<p>I'd like to store a JavaScript object in HTML5 <code>localStorage</code>, but my object is apparently being converted to a string.</p> <p>I can store and retrieve primitive JavaScript types and arrays using <code>localStorage</code>, but objects don't seem to work. Should they? </p> <p>Here's my code:</p> <pre><code>var testObject = { 'one': 1, 'two': 2, 'three': 3 }; console.log('typeof testObject: ' + typeof testObject); console.log('testObject properties:'); for (var prop in testObject) { console.log(' ' + prop + ': ' + testObject[prop]); } // Put the object into storage localStorage.setItem('testObject', testObject); // Retrieve the object from storage var retrievedObject = localStorage.getItem('testObject'); console.log('typeof retrievedObject: ' + typeof retrievedObject); console.log('Value of retrievedObject: ' + retrievedObject); </code></pre> <p>The console output is</p> <pre class="lang-none prettyprint-override"><code>typeof testObject: object testObject properties: one: 1 two: 2 three: 3 typeof retrievedObject: string Value of retrievedObject: [object Object] </code></pre> <p>It looks to me like the <code>setItem</code> method is converting the input to a string before storing it.</p> <p>I see this behavior in Safari, Chrome, and Firefox, so I assume it's my misunderstanding of the <a href="http://www.w3.org/TR/webstorage/" rel="noreferrer">HTML5 Web Storage</a> spec, not a browser-specific bug or limitation.</p> <p>I've tried to make sense of the <em>structured clone</em> algorithm described in <a href="http://www.w3.org/TR/html5/infrastructure.html" rel="noreferrer">http://www.w3.org/TR/html5/infrastructure.html</a>. I don't fully understand what it's saying, but maybe my problem has to do with my object's properties not being enumerable (???) </p> <p>Is there an easy workaround?</p> <hr> <p>Update: The W3C eventually changed their minds about the structured-clone specification, and decided to change the spec to match the implementations. See <a href="https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111" rel="noreferrer">https://www.w3.org/Bugs/Public/show_bug.cgi?id=12111</a>. So this question is no longer 100% valid, but the answers still may be of interest.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload