Interacting with the clipboard was long the bane of web app developers. Often clunky to use, at one point you even had to go through a Flash module! Those days are over, and you can now copy text in JavaScript very easily.
Copying to the clipboard in JavaScript
The least we can say is that copying text in JavaScript has gotten people talking, you can see for yourself on this StackOverflow thread… Most of the conclusions there are a bit dated, but they do a good job of showing just how tricky this question used to be.
1. The old-school way: execCommand
If your boss forces you to support outdated browser versions, you won't have any choice but to use this technique from another era. Honestly, I'm putting it here just to keep a record of it, but you shouldn't use it (that's my little archaeologist side talking):
As you can see, this is more of a slightly grimy hack than a real quality approach. You'll notice I wrote it in ES5, because if you're using this, there's a good chance your browser doesn't support ESNext syntax.
Edit : This method is deprecated and now causes issues in recent browsers. You should replace it with one of the two methods that follow.
2 . The modern version: the Clipboard API
The real solution, the one to remember, is through JavaScript's Clipboard API.
Using it has the merit of being very simple and explicit :
Careful though, your call to navigator.clipboard.writetext() must be triggered by a user action (here a click on a button).
That's why you can't just paste the line into the console of your browser to test it. This is a security measure built into browsers, I'll let you imagine the kind of nasty things some people would be tempted to do with it otherwise.
3. Advanced usage: Using a library
You might have a slightly more complex need and the Clipboard API might be a bit thin for the job:
- You want to be able to set the MIME type of the copied element (
text/htmlfor example) - You have compatibility issues with certain exotic or outdated browsers
- You want to hook events into the moment an element is copied or pasted (useful for managing your own internal clipboard system within your app while keeping it compatible with the outside world)
In that case, I can only recommend using the JavaScript library Copy To Clipboard which lets you hook events onto the copy action, set the MIME type of the copied text, and handles the most appropriate copy method for you depending on the browser (it can even fall back to execCommand if needed).
Modifying a value at the moment it's pasted
Want to modify a value at the moment it's pasted? Unfortunately, it's not going to be possible to directly modify this value to send it back to the main process. We'll need to let the value be pasted and capture the event to trigger the changes we want.
Some JS libraries handle this subtlety but aren't meant to be used in a web browser, rather in an Electron-type application. So that takes us away from our topic.






