There’s two ways to go about doing this:
Although now deprecated, but still used around quit a bit, slightly hacky and clearly an archaic way of doing this. But worth knowing about.
It works like this (check out the corresponding numbers in the example code):
copycommand and the selected text is copied into the clipboard.
Here’s the program and under is a demo for that:
The problem with the
execCommand method is that the text needs to be in a
textarea or an
input, because it needs to be selected, because the
execCommand relies on the
If the layout requires that text is not in a
textarea or an
input field, and using this method is mandatory, in that case you can have a hidden
textarea on the page:
<textarea hidden>Text</textarea>, which holds the same content as the
div, or whatever the element is.
The clipboard API has a way more modern feel to it, of course the old browsers aren’t supported, but all the moderns ones are, so it’s not a big deal.
The clipboard method lives in the navigator:
navigator.clipboard.writeText(), and it has a
writeText('foo') method that takes a string as its parameter, which is then written into the clipboard. It returns a promise, so
async functions can be used to deal with it.
The process is much simpler:
Here’s a small React app that copies using the clipboard API:
NOTE: For some reason the copy doesn’t work in the CodeSandbox frame, but it does work if you view the demo page. It just errors out with an empty Error object.
Here are all the 4 methods the
clipboard interface provides:
To sun it up: writing doesn’t need permissions, reading does.
execCommand method works on any browser and when initiated from Iframes, and what not, but the clipboard API is the way to go!
execCommand is deprecated, browsers probably won’t remove it any time soon, but you know, it’s on its way out.
Comments would go here, but the commenting system isn’t ready yet, sorry. Tweet me @hiljaa if you want to make a correction etc.