I have looked at many posts but could not find a clear current answer to the following two questions as it seems standards and browser support has been constantly changing.
Is it a legal operation according to the standard to change the clipboard with event.clipboardData.setData inside a 'copy' event handler ?
Do latest versions of Chrome/FF/Safari/IE/Chrome iOS/Android/iPhones support this correctly ?
Thanks!
You can also just turn it into a function that calls its own handler and removes it
Clipboard APIs are indeed in active development as of 2016, but here's my understanding of the current state of affairs.
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:
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 theclick
handler:Browser support varies
clipboardData
in thecopy
/cut
/paste
events (since Firefox 22) andexecCommand('copy')
from user actions (since Firefox 41)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
Async Clipboard API will provide a simpler way to manage the clipboard
When implemented,
navigator.clipboard
will let you write code like this:Chrome 66 starts shipping a partial implementation, and they've published an article about the new API.
Bind the element id with copy event and then get the selected text. You could replace or modify the text. Get the clipboard and set the new text. To get the exact formatting you need to set the type as "text/hmtl". You may also bind it to the document instead of element.