Skip to content

Commit

Permalink
Fix globals, part 14: structuredClone() (#35951)
Browse files Browse the repository at this point in the history
* move

* update link

* move
  • Loading branch information
skyclouds2001 authored Sep 26, 2024
1 parent 63297de commit 8b6cec0
Show file tree
Hide file tree
Showing 31 changed files with 103 additions and 38 deletions.
3 changes: 2 additions & 1 deletion files/en-us/_redirects.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10266,7 +10266,7 @@
/en-US/docs/Web/API/WindowOrWorkerGlobalScope/rejectionhandled_event /en-US/docs/Web/API/Window/rejectionhandled_event
/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval /en-US/docs/Web/API/setInterval
/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout /en-US/docs/Web/API/setTimeout
/en-US/docs/Web/API/WindowOrWorkerGlobalScope/structuredClone /en-US/docs/Web/API/structuredClone
/en-US/docs/Web/API/WindowOrWorkerGlobalScope/structuredClone /en-US/docs/Web/API/Window/structuredClone
/en-US/docs/Web/API/WindowOrWorkerGlobalScope/unhandledrejection_event /en-US/docs/Web/API/Window/unhandledrejection_event
/en-US/docs/Web/API/WindowSessionStorage /en-US/docs/Web/API/Window/sessionStorage
/en-US/docs/Web/API/WindowSessionStorage.sessionStorage /en-US/docs/Web/API/Window/sessionStorage
Expand Down Expand Up @@ -10745,6 +10745,7 @@
/en-US/docs/Web/API/scheduler_property /en-US/docs/Web/API/Window/scheduler
/en-US/docs/Web/API/select.type /en-US/docs/Web/API/HTMLSelectElement/type
/en-US/docs/Web/API/sessionStorage /en-US/docs/Web/API/Window/sessionStorage
/en-US/docs/Web/API/structuredClone /en-US/docs/Web/API/Window/structuredClone
/en-US/docs/Web/API/style.media /en-US/docs/Web/API/HTMLStyleElement/media
/en-US/docs/Web/API/style.type /en-US/docs/Web/API/HTMLStyleElement/type
/en-US/docs/Web/API/success /en-US/docs/Web/API/IDBRequest/success_event
Expand Down
5 changes: 3 additions & 2 deletions files/en-us/glossary/deep_copy/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,11 @@ console.log(ingredientsList[1].list);

However, while the object in the code above is simple enough to be {{Glossary("serialization", "serializable")}}, many JavaScript objects are not serializable at all — for example, [functions](/en-US/docs/Web/JavaScript/Guide/Functions) (with closures), [Symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), objects that represent HTML elements in the [HTML DOM API](/en-US/docs/Web/API/HTML_DOM_API), recursive data, and many other cases. Calling `JSON.stringify()` to serialize the objects in those cases will fail. So there's no way to make deep copies of such objects.

The web API [`structuredClone()`](/en-US/docs/Web/API/structuredClone) also creates deep copies and has the advantage of allowing [transferable objects](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) in the source to be _transferred_ to the new copy, rather than just cloned. It also handles more data types, such as `Error`. But note that `structuredClone()` isn't a feature of the JavaScript language itself — instead it's a feature of browsers and other JavaScript hosts that implement web APIs. And calling `structuredClone()` to clone a non-serializable object will fail in the same way that calling `JSON.stringify()` to serialize it will fail.
The web API {{DOMxRef("Window.structuredClone", "structuredClone()")}} also creates deep copies and has the advantage of allowing [transferable objects](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) in the source to be _transferred_ to the new copy, rather than just cloned. It also handles more data types, such as `Error`. But note that `structuredClone()` isn't a feature of the JavaScript language itself — instead it's a feature of browsers and other JavaScript hosts that implement web APIs. And calling `structuredClone()` to clone a non-serializable object will fail in the same way that calling `JSON.stringify()` to serialize it will fail.

## See also

- Related glossary terms:
- {{glossary("Shallow copy")}}
- [`window.structuredClone()`](/en-US/docs/Web/API/structuredClone)
- {{DOMxRef("Window.structuredClone()")}}
- {{DOMxRef("WorkerGlobalScope.structuredClone()")}}
2 changes: 1 addition & 1 deletion files/en-us/glossary/serializable_object/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ page-type: glossary-definition
{{GlossarySidebar}}

**Serializable objects** are objects that can be serialized and later deserialized in any JavaScript environment ("realm").
This allows them to, for example, be stored on disk and later restored, or cloned with {{domxref("structuredClone()")}}, or shared between workers using {{domxref("DedicatedWorkerGlobalScope.postMessage()")}}.
This allows them to, for example, be stored on disk and later restored, or cloned with {{DOMxRef("Window.structuredClone", "structuredClone()")}}, or shared between workers using {{domxref("DedicatedWorkerGlobalScope.postMessage()")}}.

The serialization may not include all the properties and other aspects of the original object.
For example, a serialization of a {{domxref("DOMException")}} must include the `name` and `message` properties, but whether it includes other properties is implementation dependent.
Expand Down
2 changes: 1 addition & 1 deletion files/en-us/mozilla/firefox/releases/101/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ No notable changes.

- [`HTMLInputElement.showPicker()`](/en-US/docs/Web/API/HTMLInputElement/showPicker) is now supported, allowing the picker for an input element to be displayed when a user interacts with some other element, such as a button ([Firefox bug 1745005](https://bugzil.la/1745005)).

- [`DOMException`](/en-US/docs/Web/API/DOMException) is now a {{Glossary("serializable object")}}, so it can be cloned with {{domxref("structuredClone()")}} or copied between [workers](/en-US/docs/Web/API/Worker) using {{domxref("Worker.postMessage()", "postMessage()")}} ([Firefox bug 1561357](https://bugzil.la/1561357)).
- [`DOMException`](/en-US/docs/Web/API/DOMException) is now a {{Glossary("serializable object")}}, so it can be cloned with {{DOMxRef("Window.structuredClone", "structuredClone()")}} or copied between [workers](/en-US/docs/Web/API/Worker) using {{domxref("Worker.postMessage()", "postMessage()")}} ([Firefox bug 1561357](https://bugzil.la/1561357)).

- _Constructable stylesheets_ are now supported, making it much easier to create reusable stylesheets for use with [Shadow DOM](/en-US/docs/Web/API/Web_components/Using_shadow_DOM).
The update includes the addition of a [`CSSStyleSheet()` constructor](/en-US/docs/Web/API/CSSStyleSheet/CSSStyleSheet) for creating new stylesheets, the {{domxref("CSSStyleSheet.replace()")}} and {{domxref("CSSStyleSheet.replaceSync()")}} methods that can be used to add/replace CSS rules in the sheet, and the [`Document.adoptedStyleSheets`](/en-US/docs/Web/API/Document/adoptedStyleSheets) and [`ShadowRoot.adoptedStyleSheets`](/en-US/docs/Web/API/ShadowRoot/adoptedStyleSheets) properties that are used to share sheets to a document and its shadow DOM subtrees.
Expand Down
2 changes: 1 addition & 1 deletion files/en-us/mozilla/firefox/releases/103/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ This article provides information about the changes in Firefox 103 that will aff

### APIs

- [`ReadableStream`](/en-US/docs/Web/API/ReadableStream), [`WritableStream`](/en-US/docs/Web/API/WritableStream), [`TransformStream`](/en-US/docs/Web/API/TransformStream) are now [Transferable objects](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects), which means that ownership can be transferred when sharing the objects between a window and workers using `postMessage`, or when using [`structuredClone()`](/en-US/docs/Web/API/structuredClone) to copy an object.
- [`ReadableStream`](/en-US/docs/Web/API/ReadableStream), [`WritableStream`](/en-US/docs/Web/API/WritableStream), [`TransformStream`](/en-US/docs/Web/API/TransformStream) are now [Transferable objects](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects), which means that ownership can be transferred when sharing the objects between a window and workers using `postMessage`, or when using {{DOMxRef("Window.structuredClone", "structuredClone()")}} to copy an object.
After transferring, the original object cannot be used.
See [Firefox bug 1659025](https://bugzil.la/1659025) for more details.

Expand Down
2 changes: 1 addition & 1 deletion files/en-us/mozilla/firefox/releases/104/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ No notable changes.
These are used to find the value and index (respectively) of the last element in an {{jsxref("Array")}} or {{jsxref("TypedArray")}} that matches a supplied test function.
(See [Firefox bug 1775026](https://bugzil.la/1775026) for more details.)

- Serialization of [native Error types](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#error_types) additionally includes the [`stack`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack) property when used with [`window.postMessage()`](/en-US/docs/Web/API/Window/postMessage) and [`structuredClone()`](/en-US/docs/Web/API/structuredClone) (on error types that include `stack`).
- Serialization of [native Error types](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#error_types) additionally includes the [`stack`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack) property when used with [`window.postMessage()`](/en-US/docs/Web/API/Window/postMessage) and {{DOMxRef("Window.structuredClone", "structuredClone()")}} (on error types that include `stack`).
The `stack` is not yet serialized when errors are sent using other APIs, such as [`Worker.postMessage()`](/en-US/docs/Web/API/Worker/postMessage)
(See [Firefox bug 1774866](https://bugzil.la/1774866) for more details.)

Expand Down
2 changes: 1 addition & 1 deletion files/en-us/mozilla/firefox/releases/110/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ No notable changes.

### JavaScript

- Serialization of [native Error types](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#error_types) now includes the [`stack`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack) property in workers when using [`Worker.postMessage()`](/en-US/docs/Web/API/Worker/postMessage) and [`structuredClone()`](/en-US/docs/Web/API/structuredClone).
- Serialization of [native Error types](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#error_types) now includes the [`stack`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stack) property in workers when using [`Worker.postMessage()`](/en-US/docs/Web/API/Worker/postMessage) and {{DOMxRef("Window.structuredClone", "structuredClone()")}}.
With this addition, cloning native error stacks now works for all methods that use the [structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm), in both the main thread and workers.
(See [Firefox bug 1774866](https://bugzil.la/1774866) for more details.)

Expand Down
2 changes: 1 addition & 1 deletion files/en-us/mozilla/firefox/releases/94/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ No notable changes

### APIs

- The {{domxref("structuredClone()")}} global function is now supported for copying complex JavaScript objects ([Firefox bug 1722576](https://bugzil.la/1722576)).
- The {{DOMxRef("Window.structuredClone()")}} and {{DOMxRef("WorkerGlobalScope.structuredClone()")}} function is now supported for copying complex JavaScript objects ([Firefox bug 1722576](https://bugzil.la/1722576)).

#### DOM

Expand Down
2 changes: 1 addition & 1 deletion files/en-us/web/api/console/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ If you are going to mutate your object and you want to prevent the logged inform
console.log(JSON.parse(JSON.stringify(obj)));
```

There are other alternatives that work in browsers, such as [`structuredClone()`](/en-US/docs/Web/API/structuredClone), which are more effective at cloning different types of objects.
There are other alternatives that work in browsers, such as {{DOMxRef("Window.structuredClone", "structuredClone()")}}, which are more effective at cloning different types of objects.

#### Outputting multiple objects

Expand Down
2 changes: 1 addition & 1 deletion files/en-us/web/api/domexception/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ The **`DOMException`** interface represents an abnormal event (called an **excep

Each exception has a **name**, which is a short "PascalCase"-style string identifying the error or abnormal condition.

`DOMException` is a {{Glossary("Serializable object")}}, so it can be cloned with {{domxref("structuredClone()")}} or copied between [Workers](/en-US/docs/Web/API/Worker) using {{domxref("Worker.postMessage()", "postMessage()")}}.
`DOMException` is a {{Glossary("Serializable object")}}, so it can be cloned with {{DOMxRef("Window.structuredClone", "structuredClone()")}} or copied between [Workers](/en-US/docs/Web/API/Worker) using {{domxref("Worker.postMessage()", "postMessage()")}}.

## Constructor

Expand Down
2 changes: 1 addition & 1 deletion files/en-us/web/api/rtccertificate/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ browser-compat: api.RTCCertificate

The **`RTCCertificate`** interface of the [WebRTC API](/en-US/docs/Web/API/WebRTC_API) provides an object representing a certificate that an {{domxref("RTCPeerConnection")}} uses to authenticate.

`RTCCertificate` is a {{Glossary("serializable object")}}, so it can be cloned with {{domxref("structuredClone()")}} or copied between [Workers](/en-US/docs/Web/API/Worker) using {{domxref("Worker/postMessage()", "postMessage()")}}.
`RTCCertificate` is a {{Glossary("serializable object")}}, so it can be cloned with {{DOMxRef("Window.structuredClone", "structuredClone()")}} or copied between [Workers](/en-US/docs/Web/API/Worker) using {{domxref("Worker/postMessage()", "postMessage()")}}.

## Instance properties

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Some of the functions (a subset) that are common to all workers and to the main
- {{domxref("WorkerGlobalScope.reportError()", "reportError()")}}
- {{domxref("setInterval()")}}
- {{domxref("setTimeout()")}}
- {{domxref("structuredClone()")}}
- {{DOMxRef("WorkerGlobalScope.structuredClone", "structuredClone()")}}
- {{domxref("DedicatedWorkerGlobalScope.requestAnimationFrame()", "requestAnimationFrame()")}} (dedicated workers only)
- {{domxref("DedicatedWorkerGlobalScope.cancelAnimationFrame()", "cancelAnimationFrame()")}} (dedicated workers only)

Expand Down
2 changes: 1 addition & 1 deletion files/en-us/web/api/web_workers_api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ Some of the functions (a subset) that are common to all workers and to the main
- {{domxref("WorkerGlobalScope.reportError()", "reportError()")}}
- {{domxref("setInterval()")}}
- {{domxref("setTimeout()")}}
- {{domxref("structuredClone()")}}
- {{DOMxRef("WorkerGlobalScope.structuredClone", "structuredClone()")}}
- {{domxref("DedicatedWorkerGlobalScope.requestAnimationFrame()", "requestAnimationFrame()")}} (dedicated workers only)
- {{domxref("DedicatedWorkerGlobalScope.cancelAnimationFrame()", "cancelAnimationFrame()")}} (dedicated workers only)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ page-type: 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](/en-US/docs/Web/API/Worker) via {{domxref("Worker.postMessage()", "postMessage()")}}, storing objects with [IndexedDB](/en-US/docs/Glossary/IndexedDB), or copying objects for [other APIs](#see_also).
It is used internally when invoking {{DOMxRef("WorkerGlobalScope.structuredClone", "structuredClone()")}}, to transfer data between [Workers](/en-US/docs/Web/API/Worker) via {{domxref("Worker.postMessage()", "postMessage()")}}, storing objects with [IndexedDB](/en-US/docs/Glossary/IndexedDB), or copying objects for [other APIs](#see_also).

It clones by recursing through the input object while maintaining a map of previously visited references, to avoid infinitely traversing cycles.

Expand Down Expand Up @@ -80,7 +80,8 @@ Browsers must serialize the properties `name` and `message`, and are expected to

- [HTML Specification: Safe passing of structured data](https://html.spec.whatwg.org/multipage/infrastructure.html#safe-passing-of-structured-data)
- [Transferable objects](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects)
- {{domxref("structuredClone()")}}
- {{DOMxRef("Window.structuredClone()")}}
- {{DOMxRef("WorkerGlobalScope.structuredClone()")}}
- {{domxref("window.postMessage()")}}
- [Web Workers](/en-US/docs/Web/API/Web_Workers_API)
- [IndexedDB](/en-US/docs/Web/API/IndexedDB_API)
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ For example, an {{jsxref("ArrayBuffer")}} is a transferable object that owns a b
When such a buffer is transferred between threads, the associated memory resource is detached from the original buffer and attached to the buffer object created in the new thread.
The buffer object in the original thread is no longer usable because it no longer owns a memory resource.

Transferring may also be used when creating deep copies of objects with {{domxref("structuredClone()")}}.
Transferring may also be used when creating deep copies of objects with {{DOMxRef("WorkerGlobalScope.structuredClone", "structuredClone()")}}.
Following the cloning operation, the transferred resources are moved rather than copied to the cloned object.

For both `postMessage()` and `structuredClone()`, transferred resources have to be attached to the data object, otherwise they would not be available on the receiving end, because the transferable array only indicates how certain resources should be sent, but does not actually send them (although they would always be detached).
Expand Down Expand Up @@ -48,7 +48,7 @@ console.log(uInt8Array.byteLength); // 0
## Transferring during a cloning operation

The code below shows a {{domxref("structuredClone()")}} operation where the underlying buffer is copied from the original object to the clone.
The code below shows a `structuredClone()` operation where the underlying buffer is copied from the original object to the clone.

```js
const original = new Uint8Array(1024);
Expand Down
2 changes: 1 addition & 1 deletion files/en-us/web/api/window/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ _This interface inherits methods from the {{domxref("EventTarget")}} interface._
- : Sizes the window according to its content.
- {{domxref("Window.stop()")}}
- : This method stops window loading.
- {{domxref("structuredClone", "Window.structuredClone()")}}
- {{domxref("Window.structuredClone()")}}
- : Creates a [deep clone](/en-US/docs/Glossary/Deep_copy) of a given value using the [structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
- {{domxref("Window.updateCommands()")}} {{Non-standard_Inline}}
- : Updates the state of commands of the current chrome window (UI).
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
---
title: structuredClone() global function
title: "Window: structuredClone() method"
short-title: structuredClone()
slug: Web/API/structuredClone
page-type: web-api-global-function
slug: Web/API/Window/structuredClone
page-type: web-api-instance-method
browser-compat: api.structuredClone
---

{{APIRef("HTML DOM")}}{{AvailableInWorkers}}
{{APIRef("HTML DOM")}}

The global **`structuredClone()`** method creates a [deep clone](/en-US/docs/Glossary/Deep_copy) of a given value using the [structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
The **`structuredClone()`** method of the {{domxref("Window")}} interface creates a [deep clone](/en-US/docs/Glossary/Deep_copy) of a given value using the [structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).

The method also allows [transferable objects](/en-US/docs/Web/API/Web_Workers_API/Transferable_objects) in the original value to be _transferred_ rather than cloned to the new object.
Transferred objects are detached from the original object and attached to the new object; they are no longer accessible in the original object.
Expand All @@ -32,7 +32,7 @@ structuredClone(value, options)

### Return value

The returned value is a [deep copy](/en-US/docs/Glossary/Deep_copy) of the original `value`.
A [deep copy](/en-US/docs/Glossary/Deep_copy) of the original `value`.

### Exceptions

Expand Down
2 changes: 1 addition & 1 deletion files/en-us/web/api/workerglobalscope/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ _This interface inherits methods from the {{domxref("EventTarget")}} interface._
- : Schedules a function to execute every time a given number of milliseconds elapses.
- {{domxref("setTimeout()", "WorkerGlobalScope.setTimeout()")}}
- : Schedules a function to execute in a given amount of time.
- {{domxref("structuredClone()", "WorkerGlobalScope.structuredClone()")}}
- {{domxref("WorkerGlobalScope.structuredClone()")}}
- : Creates a [deep clone](/en-US/docs/Glossary/Deep_copy) of a given value using the [structured clone algorithm](/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm).
- {{domxref("WorkerGlobalScope.reportError()")}}
- : Reports an error in a script, emulating an unhandled exception.
Expand Down
Loading

0 comments on commit 8b6cec0

Please sign in to comment.