Recently, we wanted to implement a little share button. When the user clicks it, the relevant link is added to the clipboard. This should not be too hard.
I rummaged through some of my old code and found the following snippet:
function copyToClipboard(contents) {
  var textArea = document.createElement("textarea");
  textArea.value = contents;
  textArea.style.position="fixed";  // avoid scrolling to bottom
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();
  try {
    alert(document.execCommand('copy') ? 'Successfully copied.' : 'could not copy :('); }
  catch (err) {
    alert('could not copy because ' + err);
  }
  document.body.removeChild(textArea);
}
Wow, this did not look like the 21st century. A quick search on caniuse.com showed that this code is supported by 96% of the “internet users”. But there had to be a smoother way.
There is also the Navigator.clipboard API, which still has 91.6% of support. This should be ok for such a non-essential feature. Here an example:
function copyToClipboard(contents) {
  if (typeof(navigator.clipboard) == 'undefined') { return; }
  navigator.clipboard.writeText(contents)
    .then(
      _ => alert('Successfully copied!'),
      _ => alert('could not copy :(')
    );
}
This looks much nicer and the user does not see any textareas flashing.
Happy Coding!
Resources
- Demonstration CodePen
- Stackoverflow Question
- Synchronous Clipboard API