JSON++: The Structured Clone Algorithm

I was using window.postMessage yesterday and ran into this nugget on hacks.firefox.org:

The window.postMessage() method now uses the structured clone algorithm to let you pass JavaScript objects instead of just strings from one window to another.

The Structured Clone Algorithm is an HTML5 specification for serializing complex data structures. The following are data structures that the algorithm can store that JSON cannot.

  • RegExp objects
  • Blob, File, and FileList objects
  • ImageData objects
  • Circular references

The algorithm does have some limitations:

  • Not allowed to store Error objects, Functions, or DOM objects.
  • Property descriptors, setters, and getters are not saved. Thus all objects become read write.
  • Prototype chain is not copied.

It is a wonderful upgrade to window.PostMessage! It means that you can post real data structures without having the sender use JSON.stringify and the receiver use JSON.parse. I’d like to see support in localStorage and sessionStorage.

Read the full write up on the Structured Clone Algorithm.