Copy operation can be handled using paste event:
div.addEventListener("copy", function() { ... });
The event
is cancelable and along with other event information provides DataTransfer
object:
var items = event.clipboardData;
This object has a .setData
method that should allow you to add data in clipboard. Unfortunatelly, I can't seem to figure out how does it work. Documentation is broken (if you click on setData
it navigates you on the wrong page).
I tried things like this:
function copy(event) {
var items = (event.clipboardData || event.originalEvent.clipboardData);
items.setData("image/png", _this.editor.selection.getSelectedImage());
event.preventDefault();
event.cancelBubble = true;
return false;
}
But according to MDN, the second parameter should be string too.
How can I put data in clipboard according to the specification (no browser specific functions)?
I'm the editor of the Clipboard APIs spec.
First, sorry about the broken link. It is actually working in the official TR:
http://www.w3.org/TR/clipboard-apis/
But not in the Editor's Draft, for somewhat messy process reasons (the "official" HTML5 spec dropped stuff the Clipboard API spec relies on, hard-coding a link to a specific historical snapshot of the official HTML5 spec seems like a bad idea - so I need to decide whether to simply link to the WHATWG spec or wait until a hypotethical HTML6-brings-DnD-back-in situation happens).
Now, fixing this link doesn't actually solve your problem - because even in the supposedly bleeding-edge WHATWG spec, setData() is specified as taking a string. Web technology is a work in progress, and you've come across a use case that the (older) setData() API did not take into account. This part of the API dates back to the original Microsoft implementation To be fair, JavaScript itself didn't really have convenient ways to work with binary data back then..
What you probably want to use, is the clipboardData.items.add() API passing in a File object with the relevant data and type. Note that this isn't widely implemented yet, for example AFAIK it's not supported in any current version of Firefox. You can detect the lack of clipboardData.items and .items.add(), and for example tell users to right-click an image and choose "copy to clipboard" manually.