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
.