How to copy to clipboard in Javascript?

Asked

Viewed 10,312 times

4

Which code to copy to clipboard works best in all browsers?

1 answer

5


1st Option - Function with argument

This function is a function that receives a value and automatically copies it to the clipboard. If your browser does not support error handling calls a secondary function.

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

  textArea.style.position = 'fixed';
  textArea.style.top = 0;
  textArea.style.left = 0;
  textArea.style.width = '2em';
  textArea.style.height = '2em';
  textArea.style.padding = 0;
  textArea.style.border = 'none';
  textArea.style.outline = 'none';
  textArea.style.boxShadow = 'none';
  textArea.style.background = 'transparent';
  textArea.value = text;

  document.body.appendChild(textArea);
  textArea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
    window.prompt("Copie para área de transferência: Ctrl+C e tecle Enter", text);
  }

  document.body.removeChild(textArea);
}

// Teste
var copyTest = document.querySelector('.copyTest');
copyTest.addEventListener('click', function(event) {
  copyTextToClipboard('Teste');
});
<p>
  <button class="copyTest">Copiar "Teste"</button>
</p>
<p>
  <input type="text" placeholder="Cole aqui">
</p>

Works on the following browsers: Chrome 43+, Firefox 41+, Internet Explorer 10+ and Opera 29+

Notes:

  • You can detect if the browser supports this code using:
    var copySupported = document.queryCommandSupported('copy');
  • All document.execCommand('copy') is only called if the user some direct action, such as an onClick event for example. This is done to prevent data from being copied to the clipboard without the intention of the user.

2nd Option - Manual copy via Prompt

This option opens a prompt with the value already selected and the user manually copies the code. The advantage is that it works in all browsers.

function copyToClipboard(text) {
  window.prompt("Copie para área de transferência: Ctrl+C e tecle Enter", text);
}

Source

Browser other questions tagged

You are not signed in. Login or sign up in order to post.