event.clipboardData.setData in copy event event.clipboardData.setData in copy event javascript javascript

event.clipboardData.setData in copy event


Clipboard APIs were indeed in active development as of 2016, but things have stabilized since then:

Using event.clipboardData.setData() is supported

Changing the clipboard with event.clipboardData.setData() inside a 'copy' event handler is allowed by the spec (as long as the event is not synthetic).

Note that you need to prevent the default action in the event handler to prevent your changes from being overwritten by the browser:

document.addEventListener('copy', function(e){  e.clipboardData.setData('text/plain', 'foo');  e.preventDefault(); // default behaviour is to copy any selected text});

To trigger the copy event use execCommand

If you need to trigger the copy event (and not just handle the copy requests made by the user via the browser UI), you must use document.execCommand('copy'). It will only work in certain handlers, such as the click handler:

document.getElementById("copyBtn").onclick = function() {  document.execCommand('copy');}

Modern browsers support both methods

https://github.com/garykac/clipboard/blob/master/clipboard.md has a compatibility table for execCommand(cut / copy / paste).

You can test this using the snippet below, please comment with the results.

More resources

Testcase