Cross-browser way to copy text to Clipboard

56

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

I've built a example jsFiddle , which does not work in Firefox either (infinite recursion in the copy event) or Chrome (% with% unsupported). Here is 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 would avoid this infinite recursion (it is caused by the handler that creates the ClipboardEvent , eventually capturing the event that it created itself), and that it offered a workaround in case the browser does not support ClipboardEvent .

    
asked by anonymous 25.05.2014 / 19:41

4 answers

27

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 +

More 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>
    
19.11.2015 / 16:59
23

In my particular case, it is not necessary to create a new ClipboardEvent , since I am dealing fairly 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 to make this copy (for example copying at the push of a button, instead of just handling the case where the user himself started the action via the usual controls - Ctrl + C or Right Click + Copy) this solution would not be applicable, I believe. For now, that's fine, but a more complete cross-browser would be ideal.

    
26.05.2014 / 00:57
15

Try the clipboard.js .

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

Super easy to use.

    
19.11.2015 / 16:40
1

This is a new option, but I imagine all browsers are already upgraded, ie ie 6, 7, 8, and 9 have already been.

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

It 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>
    
23.11.2015 / 16:15