In this short tutorial we’ll show you two ways of copying data to the clipboard with javascript using promises or Document execCommand(‘copy’) command.

Tags: Copy, Clipboard, Javascript, Clipboard API, Promises, Document.execCommand(‘copy’), execCommand

const copyToClipboard = str => {
  if (navigator && navigator.clipboard && navigator.clipboard.writeText)
    return navigator.clipboard.writeText(str);
  return Promise.reject('The Clipboard API is not available.');
};


Copying to the clipboard using Document.execCommand(‘copy’)

const copyToClipboard = str => {
  const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly', '');
  el.style.position = 'absolute';
  el.style.left = '-9999px';
  document.body.appendChild(el);
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
};

CC BY 4.0 no changes made – 30 Seconds of Code