How to Copy Text To Clipboard Using Javascript

How to Copy Text To Clipboard Using Javascript

1. document.execCopy

We can use document.execCopy which has widely browser support. One important to notice is that it is right now deprecated.

  • Access is synchronous
  • Text is read from the DOM and placed on the clipboard.
  • Good browser support
function fallbackCopyTextToClipboard(text) {
  var textArea = document.createElement("textarea");
  textArea.value = text;

  // Avoid scrolling to bottom
  textArea.style.top = "0";
  textArea.style.left = "0";
  textArea.style.position = "fixed";

  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Fallback: Copying text command was ' + msg);
  } catch (err) {
    console.error('Fallback: Oops, unable to copy', err);
  }

  document.body.removeChild(textArea);
}

2. Navigator.clipboard.writeText

The Clipboard API adds to the Navigator interface the read-only clipboard property, which returns the Clipboard object used to read and write the clipboard's contents.

  • writeText is used for writing contents to clipboard.
  • Access is asynchronous and uses promises.
  • Only supported on pages served over HTTPS.
navigator.clipboard.writeText(text).then(
  function() {
    console.log("Async: Copying to clipboard was successful!");
  },
  function(err) {
    console.error("Async: Could not copy text: ", err);
  }
);

3. Live Demo