Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update clipboard API docs to better represent ClipboardItem with string item data #37677

Merged
merged 8 commits into from
Jan 27, 2025
2 changes: 1 addition & 1 deletion files/en-us/web/api/clipboard/read/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ browser-compat: api.Clipboard.read
The **`read()`** method of the {{domxref("Clipboard")}} interface requests a copy of the clipboard's contents, fulfilling the returned {{jsxref("Promise")}} with the data.

The method can in theory return arbitrary data (unlike {{domxref("Clipboard.readText", "readText()")}}, which can only return text).
Browsers commonly support reading text, HTML, and PNG image data — see [browser compatibility](#browser_compatibility) for more information.
Browsers commonly support reading text, HTML, and PNG image data.

## Syntax

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

{{APIRef("Clipboard API")}} {{securecontext_header}}

The **`readText()`** method of the {{domxref("Clipboard")}} interface returns a {{jsxref("Promise")}} which fulfils with a copy of the textual contents of the system clipboard.
The **`readText()`** method of the {{domxref("Clipboard")}} interface returns a {{jsxref("Promise")}} which fulfills with a copy of the textual contents of the system clipboard.

> [!NOTE]
> To read non-text contents from the clipboard, use the {{domxref("Clipboard.read", "read()")}} method instead.
Expand Down
22 changes: 9 additions & 13 deletions files/en-us/web/api/clipboard/write/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ browser-compat: api.Clipboard.write

{{APIRef("Clipboard API")}} {{securecontext_header}}

The **`write()`** method of the {{domxref("Clipboard")}} interface writes arbitrary data to the clipboard, such as images, fulfilling the returned {{jsxref("Promise")}} on completion.
The **`write()`** method of the {{domxref("Clipboard")}} interface writes arbitrary {{domxref("ClipboardItem")}} data such as images and text to the clipboard, fulfilling the returned {{jsxref("Promise")}} on completion.
This can be used to implement cut and copy functionality.

The method can in theory write arbitrary data (unlike {{domxref("Clipboard.writeText", "writeText()")}}, which can only write text).
Browsers commonly support writing text, HTML, and PNG image data — see [browser compatibility](#browser_compatibility) for more information.
Browsers commonly support writing text, HTML, and PNG image data.

## Syntax

Expand Down Expand Up @@ -55,21 +55,17 @@ button.addEventListener("click", () => setClipboard("<empty clipboard>"));

async function setClipboard(text) {
const type = "text/plain";
const blob = new Blob([text], { type });
const data = [new ClipboardItem({ [type]: blob })];
await navigator.clipboard.write(data);
const clipboardItemData = {
[type]: text,
};
const clipboardItem = new ClipboardItem(clipboardItemData);
await navigator.clipboard.write([clipboardItem]);
}
```

The `setClipboard()` method begins by creating a new a {{domxref("Blob")}} object.
This object is required to construct a {{domxref("ClipboardItem")}} object which is sent to the clipboard.
The {{domxref("Blob")}} constructor takes in the content we want to copy and its type.
This {{domxref("Blob")}} object can be derived from many sources; for example, a [canvas](/en-US/docs/Web/API/HTMLCanvasElement).
The `setClipboard()` function specifies a `"text/plain"` MIME type in the `type` constant, then specifies a `clipboardItemData` object with a single property — its key is the MIME type, and its value is the passed in text that we want to write to the clipboard. We then construct a new {{domxref("ClipboardItem")}} object into which the `clipboardItemData` object is passed.

Next, we create a new {{domxref("ClipboardItem")}} object into which the blob will be placed for sending to the clipboard.
The key of the object passed to the {{domxref("ClipboardItem")}} constructor indicates the content type, the value indicates the content.
Then `write()` is called with `await`.
A `try..catch` block could be used to catch any errors writing the data.
Finally, `write()` is called with `await` to write the data to the clipboard.

### Write canvas contents to the clipboard

Expand Down
2 changes: 1 addition & 1 deletion files/en-us/web/api/clipboard_api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ Firefox [Web Extensions](/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with
The system clipboard is accessed through the {{domxref("Navigator.clipboard")}} global.

This snippet fetches the text from the clipboard and appends it to the first element found with the class `editor`.
Since {{domxref("Clipboard.readText", "readText()")}} (and {{domxref("Clipboard.read", "read()")}}, for that matter) returns an empty string if the clipboard isn't text, this code is safe.
Since {{domxref("Clipboard.readText", "readText()")}} returns an empty string if the clipboard isn't text, this code is safe.

```js
navigator.clipboard
Expand Down
13 changes: 8 additions & 5 deletions files/en-us/web/api/clipboarditem/clipboarditem/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ browser-compat: api.ClipboardItem.ClipboardItem
The **`ClipboardItem()`** constructor creates a new {{domxref("ClipboardItem")}} object, which represents data to be stored or retrieved via the [Clipboard API](/en-US/docs/Web/API/Clipboard_API) {{domxref("clipboard.write()")}} and {{domxref("clipboard.read()")}} methods, respectively.

> [!NOTE]
> Image format support varies by browser. See the browser compatibility table for the {{domxref("Clipboard")}} interface.
> The `read()` and `write()` methods can be used to work with text strings and arbitrary data items represented by {{domxref("Blob")}} instances. However, if you are solely working with text, it is more convenient to use the {{domxref("Clipboard.readText()")}} and {{domxref("Clipboard.writeText()")}} methods.

> [!NOTE]
> Image format support varies by browser. See the [browser compatibility table](/en-US/docs/Web/API/Clipboard#browser_compatibility) for the `Clipboard` interface.

## Syntax

Expand All @@ -24,7 +27,10 @@ new ClipboardItem(data, options)

- `data`
- : An {{jsxref("Object")}} with the {{Glossary("MIME type")}} as the key and data as the value.
The data can be represented as a {{domxref("Blob")}}, a {{jsxref("String")}} or a {{jsxref("Promise")}} which resolves to either a blob or string.
The data can be represented as one of the following:
- a {{domxref("Blob")}}
- a string
- a {{jsxref("Promise")}} that resolves to either a `Blob` or string.
- `options` {{optional_inline}}

- : An object with the following properties:
Expand All @@ -36,9 +42,6 @@ new ClipboardItem(data, options)

`inline` signifies to apps that receive the paste that the `ClipboardItem` should be inserted inline at the point of paste. `attachment` signifies to apps that receive the paste that the `ClipboardItem` should be added as an attachment. `unspecified` doesn't signify any information to apps that receive the paste.

> [!NOTE]
> You can also work with text via the {{domxref("Clipboard.readText()")}} and {{domxref("Clipboard.writeText()")}} methods of the {{domxref("Clipboard")}} interface.

## Examples

The below example requests a PNG image using {{domxref("Window/fetch", "fetch()")}}, and in turn, the {{domxref("Response.blob()")}} method, to create a new {{domxref("ClipboardItem")}}.
Expand Down
3 changes: 1 addition & 2 deletions files/en-us/web/api/clipboarditem/gettype/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ A {{jsxref("Promise")}} that resolves with a {{domxref("Blob")}} object.

## Examples

In the following example, we're returning all items on the clipboard via the {{domxref("clipboard.read()")}} method.
Then utilizing the {{domxref("ClipboardItem.types")}} property to set the `getType()` argument and return the corresponding blob object.
In the following example, we're returning all items on the clipboard via the {{domxref("clipboard.read()")}} method. For each one, we pass the {{domxref("ClipboardItem.types")}} property to the `getType()` method, which returns the corresponding `Blob` object.

```js
async function getClipboardContents() {
Expand Down
46 changes: 33 additions & 13 deletions files/en-us/web/api/clipboarditem/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,47 +7,67 @@ browser-compat: api.ClipboardItem

{{APIRef("Clipboard API")}}{{SecureContext_Header}}

The **`ClipboardItem`** interface of the [Clipboard API](/en-US/docs/Web/API/Clipboard_API) represents a single item format, used when reading or writing clipboard data using {{domxref("clipboard.read()")}} and {{domxref("clipboard.write()")}} respectively.
The **`ClipboardItem`** interface of the [Clipboard API](/en-US/docs/Web/API/Clipboard_API) represents a single item format, used when reading or writing clipboard data using {{domxref("Clipboard.read()")}} and {{domxref("Clipboard.write()")}} respectively.

The benefit of having the **`ClipboardItem`** interface to represent data, is that it enables developers to cope with the varying scope of file types and data.
The **`ClipboardItem`** interface enables developers to use a single type to represent a range of different data formats.

> [!NOTE]
> To work with text see the {{domxref("Clipboard.readText()")}} and {{domxref("Clipboard.writeText()")}} methods of the {{domxref("Clipboard")}} interface.
> The `read()` and `write()` methods can be used to work with text strings and arbitrary data items represented by {{domxref("Blob")}} instances. However, if you are solely working with text, it is more convenient to use the {{domxref("Clipboard.readText()")}} and {{domxref("Clipboard.writeText()")}} methods.

## Constructor

- {{domxref("ClipboardItem.ClipboardItem", "ClipboardItem()")}}
- : Creates a new **`ClipboardItem`** object, with the {{Glossary("MIME type")}} as the key and {{domxref("Blob")}} as the value.
- : Creates a new **`ClipboardItem`** object, with the {{Glossary("MIME type")}} as the key and the data as the value.

## Instance properties

_This interface provides the following properties._

- {{domxref("ClipboardItem.types", "types")}} {{ReadOnlyInline}}
- : Returns an {{jsxref("Array")}} of MIME types available within the **`ClipboardItem`**.
- {{domxref("ClipboardItem.presentationStyle", "presentationStyle")}} {{ReadOnlyInline}}
- : Returns one of the following: `"unspecified"`, `"inline"` or `"attachment"`.

## Static methods

_This interface defines the following methods._

- {{domxref("ClipboardItem.supports_static", "ClipboardItem.supports()")}}
- : Checks whether a given {{Glossary("MIME type")}} is supported by the clipboard. This enables a website to detect whether a MIME type is supported by the clipboard before attempting to write data.
- : Checks whether a given {{Glossary("MIME type")}} is supported by the clipboard. This enables a website to detect whether a MIME type is supported before attempting to write data.

## Instance methods

_This interface defines the following methods._

- {{domxref("ClipboardItem.getType", "getType()")}}
- : Returns a {{jsxref("Promise")}} that resolves with a {{domxref("Blob")}} of the requested {{Glossary("MIME type")}}, or an error if the MIME type is not found.

## Examples

### Writing to the clipboard
### Writing text to the clipboard

In this example we first define two constants containing references to a {{htmlelement("p")}} element containing some text and a {{htmlelement("button")}} element.

Next, we define a function called `copyToClipboard()`. This starts off by storing a `"text/plain"` MIME type in a constant, then creating an object called `clipboardItemData` that contains one property with a key equal to the MIME type and a value of the text we want to copy to the clipboard (the content of the `<p>` element, in this case). Because we are working with text, we can pass it in directly rather than having to create a {{domxref("Blob")}}.

We construct a new `ClipboardItem` object using the {{domxref("ClipboardItem.ClipboardItem", "ClipboardItem()")}} constructor, and pass it into the {{domxref("Clipboard.write()")}} method to copy the text to the clipboard.

Finally, we add an event listener to the `<button>` so that it runs the function when pressed.

```js
const textSource = document.querySelector("p");
const copyBtn = document.querySelector("button");

async function copyToClipboard() {
const type = "text/plain";
const clipboardItemData = {
[type]: textSource.textContent,
};
const clipboardItem = new ClipboardItem(clipboardItemData);
await navigator.clipboard.write([clipboardItem]);
}

copyBtn.addEventListener("click", copyToClipboard);
```

### Writing an image to the clipboard

Here we use {{domxref("ClipboardItem.supports_static", "supports()")}} to check whether the `image/svg+xml` MIME data type is supported.
If it is, we fetch the image with the ["Fetch API"](/en-US/docs/Web/API/Fetch_API), and then read it into a {{domxref("Blob")}}, which we can use to create a `ClipboardItem` that is written to the clipboard.
If it is, we fetch an SVG image with the [Fetch API](/en-US/docs/Web/API/Fetch_API), and then read it into a {{domxref("Blob")}}, which we can use to create a `ClipboardItem` that is written to the clipboard.

```js
async function writeClipImg() {
Expand Down
6 changes: 3 additions & 3 deletions files/en-us/web/api/clipboarditem/supports_static/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ supports(type)

- `type`

- : A string, indicating the {{Glossary("MIME type")}} to test.
- : A string indicating the {{Glossary("MIME type")}} to test.

These MIME types are always supported:

Expand All @@ -45,10 +45,10 @@ supports(type)

### Writing an image to the clipboard

The following example fetches an SVG image to a blob, and then writes it to the clipboard.
The following example fetches an SVG image, represents it as a {{domxref("Blob")}}, and then writes it to the clipboard.

We use `supports()` to check whether the `"image/svg+xml"` MIME type is supported by the clipboard before fetching the image and writing it using {{domxref("clipboard.write()")}}.
We also wrap the whole function body in [`try..catch`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) statement to catch any other errors, such as `ClipboardItem` itself not being supported.
We also wrap the whole function body in a [`try...catch`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) statement to catch any other errors, such as `ClipboardItem` itself not being supported.

```js
async function writeClipImg() {
Expand Down
5 changes: 2 additions & 3 deletions files/en-us/web/api/clipboarditem/types/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,15 @@ browser-compat: api.ClipboardItem.types

{{APIRef("Clipboard API")}} {{securecontext_header}}

The read-only **`types`** property of the {{domxref("ClipboardItem")}} interface returns an {{jsxref("Array")}} of {{Glossary("MIME type", 'MIME types')}} available within the {{domxref("ClipboardItem")}}
The read-only **`types`** property of the {{domxref("ClipboardItem")}} interface returns an {{jsxref("Array")}} of {{Glossary("MIME type", 'MIME types')}} available within the {{domxref("ClipboardItem")}}.

## Value

An {{jsxref("Array")}} of available {{Glossary("MIME type", 'MIME types')}}.

## Examples

In the below example, we're returning all items on the clipboard via the {{domxref("Clipboard.read()")}} method.
Then checking the `types` property for available types before utilizing the {{domxref("ClipboardItem.getType()")}} method to return the {{domxref("Blob")}} object. If no clipboards contents is found for the specified type, an error is returned.
In the below example, we're returning all items on the clipboard via the {{domxref("Clipboard.read()")}} method, then checking the `types` property for available types before utilizing the {{domxref("ClipboardItem.getType()")}} method to return each data item as a {{domxref("Blob")}}. If no clipboard contents is found for the specified type, an error is returned.

```js
async function getClipboardContents() {
Expand Down
Loading