javascript – Cross-browser way to copy text to the Clipboard (Clipboard)

Question:

I'm looking for ways to copy text to the clipboard via JavaScript, which works in most modern browsers, but there's too much information and it seems out of date. I know 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 can only find examples that use ClipboardEvent – which is precisely the part that is not yet widely supported.

I've put together an example jsFiddle , which doesn't work in either Firefox (infinite recursion on copy event) or Chrome ( ClipboardEvent not supported). Here's 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 that it created itself), and that offers a workaround in case the browser doesn't support the ClipboardEvent .

Answer:

Browser Support

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

  • 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>
Scroll to Top