There are 3 main ways you can copy something to clipboard with JavaScript. The main one is the Async Clipboard API. It reads the text from DOM and places it on the clipboard.

The Async Clipboard API is essentially an object navigator.clipboard. It’s available only on pages served via HTTPS.

To write something to a clipboard use the function navigator.clipboard.writeText.

It returns a promise that resolves when the text is successfully written to the clipboard.

  .then(function() {
    console.log('Copying to clipboard was successful!');
  }, function(err) {
    console.error('Could not copy text to clipboard.', err);

The Async Clipboard API won’t be available in the old browsers, so you should either provide a fallback or display an error message if the object navigator.clipboard is missing.

  if (!navigator.clipboard) {
    fallbackCopyToClipboard(text);  // or show an error message

The fallback function may look like this.

function fallbackCopyToClipboard(text) {
  var textArea = document.createElement("textarea");
  textArea.value = text;

  try {
    var isCopySuccessful = document.execCommand('copy');
  } catch (err) {
    console.error('an error occurred while copying text to clipboard', err);


Here we’ve created a textArea, put the text in it and then immediately copied this text to clipboard using the document.execCommand('copy') function.

Eventually we remove the textArea from DOM with document.body.removeChild(textArea).