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.

  navigator.clipboard.writeText(text)
  .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
    return;
  }

The fallback function may look like this.

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

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

  document.body.removeChild(textArea);
}

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).