Cross-browser way of copying text to the Clipboard (Clipboard)

Asked

Viewed 16,863 times

57

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

I rode a jsFiddle of example, that doesn’t even work in Firefox (infinite recursion in the event copy) nor in Chrome (ClipboardEvent unsupported). 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 captures the event he created), and offers a workaround pro in case the browser does not support the ClipboardEvent.

  • 3

    A good alternative is to use the http://zeroclipboard.org library, which uses flash.

  • 3

    I also needed this in the recent past. Researching found that Rich Text editors used the document.execCommand, but it seems that this feature has stopped working on Chrome and Firefox for security reasons. This page has some compatibility information of this method (and a test page bacana): http://www.quirksmode.org/dom/execCommand.html At the time I needed it I ended up using a Flash bridge, as suggested by @Gabrielsantos.

  • Thanks, I’ll take a look at your suggestions. For now I’m not in a hurry, so I prefer to wait for a solution via HTML5 that does not depend on the Flash. But if there are none, I will consider these alternatives.

4 answers

29


Support from the Browsers

The support of 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>

  • 3

    That’s good news! When I wrote the question there was no such support, and it was limited to elements in "design mode" (contentEditable I think). I will wait a little longer, but I must accept your answer, because it seems to be in fact the most standardized way that we have to access Clipboard (and the library Clipboard.js suggested by Hezekiah aid). Note: for the same security reasons already mentioned, the above code only works in response to a user interaction; if the function is placed in a setTimeout for example the execCommand glitch.

  • 5

    @mgibsonbr True, browsers allow the use of execCommand() only for user actions, this is a way to prevent certain problems, like popup, , look at the amount of actions this function does: http://codepen.io/netsi1964/fullQbLGW/

  • 1

    Wow, I had no idea there were all these possibilities, how interesting.

  • 2

    I’ve tested it on several browsers, and it’s okay. The interesting thing is that Internet Explorer is the only one that asks for confirmation from the user to access the clipboard (such as the old behavior), which is a shame, because everyone should do it...

  • 1

    @Alexandrec.Caus If my answer has solved your doubt the reward will be welcome ;)

  • @Gabrielrodrigues , I am satisfied with your answer, I was just waiting for more firewood from the other users, haha, but it seems clear that there is not much secret!

Show 1 more comment

24

In my particular case, there is no need to create a new ClipboardEvent, because I am dealing precisely with an event of copy or paste. In this case, just 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 on Chrome, Firefox, and Opera, but failed on IE11 and Safari. Also, if I wanted to use a command of my own to make that copy (for example copying by pressing a button, instead of just dealing with the case where the user started the action himself 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.

15

Try the Clipboard.js.

You don’t use Flash. It has no dependencies. Only 2kb.

Super easy to use.

  • 3

    It seems to work well, I will do some tests. From what I read it is based on execCommand and in the Selection. When I wrote this question there was not much support, but I see that things have improved a lot... :)

  • After your tests, please share with us what you ended up using, so more people will benefit. Hugs! D

  • Ih, I asked this question a year and a half ago, I don’t even remember what project I needed it on, but in the end I ended up using my own answer (because my particular case was simpler than I expected). As for testing, this library worked well on all browsers I have tested, except Safari of course (which does not yet support execCommand). Now, if I were to use it in practice, I would probably do it "raw" even (i.e. as the answer goes), unless I found some particular advantage in this library that was difficult).

1

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

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

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

Try it like 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>

Browser other questions tagged

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