How to work with clipboard

Clipboard API consits from following classes:

  1. Clipboard - provides reading and writing text and data to or from the system clipboard. All object methods are asynchronous (the specification refers to this as the 'Async Clipboard API).
  2. ClipboardEvent - represents events providing information related to modification of the clipboard.
  3. ClipboardItem - represents a single item format, used when reading or writing data.

The Clipboard API can be used to implement cut, copy, and paste features within a web application.

The system clipboard is exposed through the global navigator.clipboard property.

Calls to the methods of the Clipboard object will not succeed if the user hasn't granted the needed permissions. Pages in active tabs can write to the clipboard without requesting permission, but reading from the clipboard always requires permission.

In some browsers Clipboard API is available only for HTTPS pages.

clipboard permissions

You can check permissions before working with clipboard.

navigator.permissions.query({name: "clipboard-write"}).then(result => {
  if (result.state == "granted" || result.state == "prompt") {
    /* write to the clipboard now */
  }
});

navigator.permissions.query({name: "clipboard-read"}).then(result => {
  if (result.state == "granted" || result.state == "prompt") {
    /* read data from clipboard */
  }
});

If you want to use the clipboard in an <iframe> you should grant permissions.

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

text clipboard

code snippets
// copy text from <textarea> or <input>
var txt = document.getElementById('txtSrc').value;
navigator.clipboard.writeText(txt);

// copy text from non-form element such <div> 
var txt = document.getElementById('txtSrc').textContent;
navigator.clipboard.writeText(txt);

// copy text and check is operation was successful
navigator.clipboard.writeText(txt).then(function() {
    /* clipboard successfully set */
  }, function() {
    /* clipboard write failed */
  });

// read text from clipboard to element such <div>
navigator.clipboard.readText().then(
  clipText => document.getElementById('txtDst').innerText = clipText);

live demo


Default initial text

There is also old way using document.execCommand() method. It has less convenience. You must select text only from <textarea> or <input>, not from <div>. Then run command document.execCommand('copy'). If you want copy content from <div> you must use textarea/input as an intermediate step. Also it does not work on background pages.

image clipboard

Currently clipboard support only png images.

Image must be converted to Blob object for writig to clipboard.

Firefox and Safari don't support the ClipboardItem class yet.

code snippets
fetch('/images/cyclist.png') // load image by url
  .then(response => response.blob())
  .then(imgData => { // write image blob to clipboard 
          var clipItem = new ClipboardItem({'image/png': imgData});
          navigator.clipboard.write([clipItem]);                 
      });

// Get content of canvas as Blob object.
// Actually "image/png" is default value, and can be omitted.
canvas.toBlob(canvasBlob =>{
    var clipItem = new ClipboardItem({'image/png': canvasBlob});
    navigator.clipboard.write([clipItem]); 
}, "image/png");
  

// Try read image from the first ClipboardItem object.
// You can extend the code to check all available objects.
navigator.clipboard.read()
  .then( data => { data[0].getType('image/png')
       .then(imgBlob => {
           var fr = new FileReader();
           
           fr.onload = frEvent => {
               var img = document.getElementById('dstImg');
               img.src = frEvent.target.result;
           }
                 
           fr.readAsDataURL(imgBlob);
        });
            
   },
   err => console.log('Image not found in clipboard, got exception: ', err)
   ); 
live demo