title | slug | page-type | tags | |||||
---|---|---|---|---|---|---|---|---|
The structured clone algorithm |
Web/API/Web_Workers_API/Structured_clone_algorithm |
guide |
|
{{DefaultAPISidebar("Web Workers API") }}
The structured clone algorithm copies complex JavaScript objects. It is used internally when invoking {{domxref("structuredClone()")}}, to transfer data between Workers via {{domxref("Worker.postMessage()", "postMessage()")}}, storing objects with IndexedDB, or copying objects for other APIs.
It clones by recursing through the input object while maintaining a map of previously visited references, to avoid infinitely traversing cycles.
-
{{jsxref("Function")}} objects cannot be duplicated by the structured clone algorithm; attempting to throws a
DataCloneError
exception. -
Cloning DOM nodes likewise throws a
DataCloneError
exception. -
Certain object properties are not preserved:
- The
lastIndex
property of {{jsxref("RegExp")}} objects is not preserved. - Property descriptors, setters, getters, and similar metadata-like features are not duplicated. For example, if an object is marked readonly with a property descriptor, it will be read/write in the duplicate, since that's the default.
- The prototype chain is not walked or duplicated.
- The
Object type | Notes |
---|---|
All primitive types | However, not symbols. |
{{jsxref("Boolean")}} objects | |
{{jsxref("String")}} objects | |
{{jsxref("Date")}} | |
{{jsxref("RegExp")}} | lastIndex is not preserved. |
{{domxref("Blob")}} | |
{{domxref("File")}} | |
{{domxref("FileList")}} | |
{{jsxref("ArrayBuffer")}} | |
{{jsxref("TypedArray")}} | |
{{jsxref("DataView")}} | |
{{domxref("ImageBitmap")}} | |
{{domxref("ImageData")}} | |
{{jsxref("Array")}} | |
{{jsxref("Object")}} | Only plain objects (e.g. from object literals) |
{{jsxref("Map")}} | |
{{jsxref("Set")}} | |
{{domxref("DOMException")}} | Most browsers only clone the properties {{domxref("DOMException.name","name")}} and {{domxref("DOMException.message","message")}} (in theory stack traces and other attributes may also be cloned). |
Native Error types |
The error name must be one of: {{jsxref("Error")}}, {{JSxRef("EvalError")}}, {{JSxRef("RangeError")}}, {{JSxRef("ReferenceError")}}, {{JSxRef("SyntaxError")}}, {{JSxRef("TypeError")}}, {{JSxRef("URIError")}} (or will be set to "Error"). Browsers must serialize the properties {{JSxRef("AggregateError")}} support is expected to be added to the specification in whatwg/html#5749 (and is already supported in some browsers). |
- HTML Specification: Safe passing of structured data
- {{Glossary("Transferable objects")}}
- {{domxref("structuredClone()")}}
- {{domxref("window.history")}}
- {{domxref("window.postMessage()")}}
- Web Workers
- IndexedDB