Cross-browser way of copying text to Clipboard)

I'm looking for ways to copy a text to the clipboard ( clipboard ) via JavaScript, which works in most modern browsers, but there is too much information and it seems outdated to me. I know that there is the Clipboard API and that it is partially supported by everyone (except Firefox, which fully implements it). I would like to use it, but I only find examples that use ClipboardEvent - which is precisely the part not yet widely support.

I mounted an example jsfiddle , which does not work either in Firefox (infinite recursion in event copy) or Chrome (ClipboardEvent not supported). Follow the code:

$("textarea").bind("copy cut", function(e) {
    e.preventDefault();
    e.stopPropagation();

    // Fonte: http://stackoverflow.com/a/16036818/520779
    var textComponent = this;
    var startPos = textComponent.selectionStart;
    var endPos = textComponent.selectionEnd;
    var selectedText = textComponent.value.substring(startPos, endPos);

    var exemploTransformacao = selectedText.toUpperCase();

    // Fonte: https://datatables.net/blog/2014-01-31
    var clip = new ClipboardEvent('copy');
    clip.clipboardData.setData('text/plain', exemploTransformacao);
    clip.preventDefault();

    e.target.dispatchEvent(clip);
});

I would like an example that avoids this infinite recursion (it is caused because the handler that creates the ClipboardEvent ends up capturing the event it created itself), and that offers a workaround pro if the browser does not support the ClipboardEvent.

Author: mgibsonbr, 2014-05-25

4 answers

Browser support

Support for Document.ExecCommand ('copy') has grown, take a look at the list of supported:

  • IE8 +
  • Google Chrome 43 +
  • Mozilla Firefox 40 +
  • Opera 32 +
  • iOS Safari 8.4 +
  • Android Browser 4.1 +

In more detail in: Can I use Document.execCommand()

Example:

var copyTextareaBtn = document.querySelector('.copiar');

copyTextareaBtn.addEventListener('click', function(event) {
  var copyTextarea = document.querySelector('.textarea');
  copyTextarea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'sim!' : 'não!';
    alert('Texto copiado? ' + msg);
  } catch (err) {
    alert('Opa, Não conseguimos copiar o texto, é possivel que o seu navegador não tenha suporte, tente usar Crtl+C.');
  }
});
<textarea class="textarea">Vamos copiar este texto?</textarea>
<br>
<button class="copiar">Copiar Texto</button>
 29
Author: Gabriel Rodrigues, 2015-11-24 00:59:45

In my particular case, it is not necessary to create a new ClipboardEvent, since I am dealing precisely with an event of copy or paste. In this case, simply locate the original event, and assign the value to be sent to the clipboard:

e.originalEvent.clipboardData.setData("text", exemploTransformacao);

Example in jsFiddle . This example worked successfully in Chrome, Firefox, and Opera, but failed in IE11 and Safari. Also, if I wanted to use a command of my own to make this copy (e.g. copy on pressing a button, instead of just dealing with the case where the user himself initiated the action via the usual controls - Ctrl + C or Right Click + Copy) this solution would not be applicable, I believe. For now this suits me, but a more complete solution and really cross-browsers would be ideal.

 23
Author: mgibsonbr, 2014-05-25 22:57:07

Try a clipboard.js .

Does not use Flash. It has no dependencies. Only 2kb.

Super easy to use.

 14
Author: Ezequias Dinella, 2015-11-19 15:40:29

This is a new option, but I imagine all browsers are already up to date, it was ie 6, 7, 8 and 9 was already.

Works using the document command.execCommand('copy');. With this command you will copy anything that is selected. Including spans, divs, anything!

Works on Internet Explorer 10+, Chrome 43+, Opera 29+, and Firefox 41+.

Try This:

// setup the varriables
var textarea = document.getElementById("textarea");
var answer = document.getElementById("copyAnswer");
var copy   = document.getElementById("copyBlock");
copy.addEventListener('click', function(e) {

   textarea.select(); 

   try {

       // The important part (copy selected text)
       var successful = document.execCommand('copy');

       if(successful) answer.innerHTML = 'Copiado!';
       else answer.innerHTML = 'Não foi possível copiar!';
   } catch (err) {
       answer.innerHTML = 'Navegador sem suporte!';
   }
});

Html:

<textarea id="textarea" rows="6" cols="40">
Lorem ipsum dolor sit amet, eamsemper maiestatis no.
</textarea><br/>

<button id="copyBlock">Clique para copiar</button> <span id="copyAnswer"></span>
 0
Author: Igor Quirino, 2015-11-23 15:15:47