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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const copyToClipboard = str => {
if (navigator && navigator.clipboard && navigator.clipboard.writeText)
return navigator.clipboard.writeText(str);
return Promise.reject('The Clipboard API is not available.');
};
const copyToClipboard = str => { if (navigator && navigator.clipboard && navigator.clipboard.writeText) return navigator.clipboard.writeText(str); return Promise.reject('The Clipboard API is not available.'); };
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’)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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);
};
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); };
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