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
.
A good alternative is to use the http://zeroclipboard.org library, which uses flash.
– user622
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.– Luiz Vieira
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.
– mgibsonbr