How to read from and write to the clipboard in JavaScript

We can interact with the system clipboard in two ways:

  • using the document.execCommand
  • using the asynchronous Clipboard API

1. Using the document.execCommand

  • document.execCommand("copy"): copy the selected text
  • document.execCommand("cut"): cut the selected text
  • document.execCommand("paste"): paste the text in the clipboard

Copy text in a span by clicking on it

The problem with the execCommand command is that we can only cut or copy the selected text. To overcome this, we can use the Clipboard API.

2. Using the Clipboard API

Using the Clipboard API, we can specify what information is to be placed in the system clipboard. Then, the Clipboard API performs operations asynchronously.

Check if the browser supports the Clipboard API

if (navigator.clipboard) {
  // yes 😎 
} else {
  // nope 😢
}

Write text to the clipboard

navigator.clipboard.writeText("TEXT_TO_BE_COPIED")
         .then(() => alert("Copied"))

Read text from the clipboard

navigator.clipboard.readText()
         .then(() => alert("Copied"))

Don’t try the above code in the console. To use the Clipboard API, the document needs to be in a focused state. Otherwise, a DOMException will be thrown.

If you need to use the Clipboard API in an iframe, then set iframe permissions to allow clipboard read/write operations.

<iframe
    src="ifram_index.html"
    allow="clipboard-read; clipboard-write"
>
</iframe>

The Clipboard API is not limited to copying and pasting text. It can also be used to copy and paste images.

Copy an image using the Clipboard API

To copy an image, we need an image blob and we need to write the blob to the clipboard. When clicking the image, we will copy the image to the clipboard.

Our image tag is:

// HTML;
<img id="img" src="imgfile.png" alt="image" title="click to copy" />

To copy an image to the clipboard, first convert the image to a blob, and then write it as a ClipboardItem with the key as the image type and the value as the image blob.

//js

async function convertImageToBlob(ele) {
   let canvas = document.createElement('canvas');
   canvas.width = img.clientWidth;
   canvas.height = img.clientHeight;

   let context = canvas.getContext('2d');
   // copy image to 
   context.drawImage(img, 0, 0);

   // toBlob is async operation
   let blob = await canvas.toBlob(blob => blob);
   return blob;
}


let img = document.getElementById('img');

img.onclick = async () =>{
   let blob = await convertImageToBlob(img);
   try {
      await navigator.clipboard.write([
         new ClipboardItem({
            [blob.type]: blob //storing in clipboard
         })
     ]);
     console.log('Image copied.');
   } catch (err) {
     console.error(err.name, err.message);
   } 
};

Let’s write code to read the image from the clipboard. We will read the available blob data using the read method – it will return the clipboardItems.

async function getClipboardContents() {
  try {
    const clipboardItems = await navigator.clipboard.read();
    for (const clipboardItem of clipboardItems) {
      for (const type of clipboardItem.types) {
        const blob = await clipboardItem.getType(type);
        console.log(URL.createObjectURL(blob)); //image as url
      }
    }
  } catch (err) {
    console.error(err.name, err.message);
  }
}