Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. Clipboard
  4. write()

Clipboard: write() method

Baseline 2024
Newly available

Since June 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

Secure context: This feature is available only insecure contexts (HTTPS), in some or allsupporting browsers.

Thewrite() method of theClipboard interface writes arbitraryClipboardItem data such as images and text to the clipboard, fulfilling the returnedPromise on completion.This can be used to implement cut and copy functionality.

The method can in theory write arbitrary data (unlikewriteText(), which can only write text).Browsers commonly support writing text, HTML, and PNG image data.

Syntax

js
write(data)

Parameters

data

An array ofClipboardItem objects containing data to be written to the clipboard.

Return value

APromise which is resolved when the data has been written to the clipboard.Note that if the underlying OS does not support multiple native clipboard items on the system clipboard, then only the firstClipboardItem in the array is written.

The promise is rejected if the clipboard is unable to write to the clipboard.

Exceptions

NotAllowedErrorDOMException

Thrown if writing to the clipboard is not allowed.

Security considerations

Writing to the clipboard can only be done in asecure context.

Additional security requirements are covered in theSecurity consideration section of the API overview topic.

Examples

Write text to the clipboard

This example function replaces the current contents of the clipboard with a specified string when a button is pressed.Note that for this particular case, you could just as readily useClipboard.writeText().

js
button.addEventListener("click", () => setClipboard("<empty clipboard>"));async function setClipboard(text) {  const type = "text/plain";  const clipboardItemData = {    [type]: text,  };  const clipboardItem = new ClipboardItem(clipboardItemData);  await navigator.clipboard.write([clipboardItem]);}

ThesetClipboard() function specifies a"text/plain" MIME type in thetype constant, then specifies aclipboardItemData 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 newClipboardItem object into which theclipboardItemData object is passed.

Finally,write() is called withawait to write the data to the clipboard.

Write canvas contents to the clipboard

This example draws a blue rectangle to the canvas.You can click the rectangle to copy the content of the canvas into the clipboard as an image, and then select another element and paste in the content from the clipboard.

HTML

The HTML just defines our<canvas> element and the<div> element with idtarget where the canvas image will be pasted.

html
<canvas width="100" height="100"></canvas><div>Paste here.</div>
<pre></pre>
#log {  height: 60px;  overflow: scroll;  padding: 0.5rem;  border: 1px solid black;}
js
const logElement = document.querySelector("#log");function log(text) {  logElement.innerText = `${logElement.innerText}${text}\n`;  logElement.scrollTop = logElement.scrollHeight;}

JavaScript

First we define anasync function to copy a canvas to a blob.This wraps the old callback-styleHTMLCanvasElement.toBlob() method into the more intuitivePromise based function.

js
// Async/await method replacing toBlob() callbackasync function getBlobFromCanvas(canvas) {  return new Promise((resolve, reject) => {    canvas.toBlob((blob) => {      if (blob) {        resolve(blob);      } else {        reject(new Error("Canvas toBlob failed"));      }    });  });}

Next we set up our canvas and add an event listener for theclick event.

When you click the blue rectangle, the canvas displaying the rectangle is copied into a blob, and then the blob is added to aClipboardItem and then written to the clipboard.

js
const canvas = document.getElementById("canvas");// Set up canvasconst ctx = canvas.getContext("2d");ctx.fillStyle = "cornflowerblue";ctx.fillRect(0, 0, 100, 100);canvas.addEventListener("click", copyCanvasContentsToClipboard);const target = document.getElementById("target");async function copyCanvasContentsToClipboard() {  // Copy canvas to blob  try {    const blob = await getBlobFromCanvas(canvas);    // Create ClipboardItem with blob and it's type, and add to an array    const data = [new ClipboardItem({ [blob.type]: blob })];    // Write the data to the clipboard    await navigator.clipboard.write(data);    log("Copied");  } catch (error) {    log(error);  }}

Note that if you are fetching a less-common file type or a resource that you don't know the type in advance, you may want to useClipboardItem.supports() to check if the file type is supported, and provide a good error message to the user in case it isn't.

We then define an event listener forpaste events on then element where we want to display the clipboard contents as an image.TheFileReader API allows us to read the blob using thereadAsDataUrl method and create an<img> element with the canvas contents:

js
target.addEventListener("paste", (event) => {  const items = (event.clipboardData || window.clipboardData).items;  const blob = items[0].getAsFile();  const reader = new FileReader();  reader.addEventListener("load", (event) => {    const img = new Image();    img.src = event.target.result;    target.appendChild(img);  });  reader.readAsDataURL(blob);});
body {  font-family: sans-serif;}#target {  border: 2px solid;  padding: 1rem;  height: 150px;}img {  margin: 0.5rem;}

Result

The result is shown below.First click on the blue square, and then select the text "Paste here" and use your OS-specific keyboard combinations to paste from the clipboard (such asCtrl+V on Windows).

Specifications

Specification
Clipboard API and events
# dom-clipboard-write

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp