Lower, Copy and Paste in JavaScript

The browser permits JavaScript scripts to learn and write to the clipboard, and routinely copy or paste content material. Basically, scripts mustn’t modify the consumer’s clipboard, in order to not meet the consumer’s expectations. Nevertheless, generally it may be handy to do that, such because the “one-click copy” perform, the consumer clicks a button, and the desired content material is routinely entered into the clipboard. At the moment, there are 3 ways to implement clipboard operations.
- Doc.execCommand()methodology
- Asynchronous Clipboard API
- copy,lower and paste Occasions
This text introduces these three strategies one after the other. That is my thirty seventh Medium article.
Doc.execCommand() methodology
Doc.execCommand() is the normal methodology of manipulating the clipboard, which is supported by numerous browsers. It helps the three operations of copy, lower, and paste.
- Doc.execCommand('copy') — copy
- Doc.execCommand('lower') — lower
- Doc.execCommand('paste') — paste
Copy or Lower operation
When copying, first choose the textual content after which name the Doc.execCommand('copy'), the chosen textual content will enter the clipboard.
https://medium.com/media/9d3d2c9d872794a6960dac276cdafef3/href
Within the above instance, the script first selects the textual content within the inputElement of the enter field ( inputElement.choose() ), after which Doc.execCommand('copy') copies it to the clipboard. Notice that the copy operation is greatest positioned within the occasion listener perform, triggered by the consumer (for instance, the consumer clicks a button). If the script is executed autonomously, some browsers could report an error. Lower operation can also be much like the copy operation.
https://medium.com/media/2c370cdc565840fc90b9b2d114951405/href
Paste operation
When pasting, calling Doc.execCommand('paste') will output the contents of the clipboard to the present focus ingredient.
https://medium.com/media/87c5e442a7018036dfc607514de7c9af/href
Drawback
Though the Doc.execCommand() methodology is handy, it has some disadvantages. First, it could actually solely copy the chosen content material to the clipboard, and can’t write content material to the clipboard arbitrarily. Secondly, it’s an asynchronous operation. In the event you copy/paste a considerable amount of knowledge, the web page will freeze. Some browsers will even pop up a immediate field and ask the consumer for permission. Presently, the web page will develop into unresponsive earlier than the consumer makes a selection. So as to resolve these issues, browser distributors have proposed an asynchronous Clipboard API.
Asynchronous Clipboard API
Clipboard API is the next-generation clipboard operation methodology, which is extra highly effective and affordable than the normal Doc.execCommand() methodology. All its operations are asynchronous and return Promise objects with out inflicting web page jams. Furthermore, it could actually put arbitrary content material (corresponding to footage) into the clipboard. The navigator.clipboard property returns the Clipboard object, and all operations are carried out by means of this object.
const clipboardObj = navigator.clipboard;
If the navigator.clipboard property returns undefined, it signifies that the present browser doesn’t assist this API (you possibly can see the complete compatibly desk on Can I exploit…). Since customers could put delicate knowledge (corresponding to passwords) on the clipboard, permitting scripts to learn them arbitrarily will trigger safety dangers, so this API has extra safety restrictions. Initially, the Chrome browser stipulates that solely HTTPS protocol pages can use this API. Nevertheless, the event setting (localhost) permits using non-encrypted protocols. Secondly, the consumer’s permission must be clearly obtained when calling. The particular implementation of permissions makes use of the Permissions API. There are two permissions associated to the clipboard: clipboard-write (write permission) and clipboard-read (learn permission). The “write permission” is routinely granted to the script, and the “learn permission” should be explicitly granted by the consumer. In different phrases, the script might be routinely accomplished when writing to the clipboard, however when studying the clipboard, the browser will pop up a dialog field asking whether or not the consumer agrees to learn.

As well as, it must be famous that what the script reads is at all times the clipboard of the present web page. One downside that this brings is that if you happen to paste the related code into the developer instrument and run it instantly, an error could also be reported as a result of the present web page presently is the window of the developer instrument, not an online web page.
https://medium.com/media/c917e180df44ce0caf0e422b013fb7c6/href
In the event you paste the above code into the developer instrument and run it, an error can be reported. As a result of when the code is working, the developer instrument window is the present web page, and there’s no DOM interface that the Clipboard API is dependent upon this web page. One resolution is to place the related code in setTimeout() to delay working, and rapidly click on on the web page window of the browser earlier than calling the perform to show it into the present web page.
https://medium.com/media/d4a86d5bd7042b55a12b262e7de204b8/href
After the above code is pasted into the developer instrument to run, rapidly click on on the web page window of the webpage to make it the present web page, in order that no error can be reported.
Clipboard object
clipboard.readText()
The clipboard.readText() methodology is used to repeat the textual content knowledge within the clipboard.
https://medium.com/media/edbdd6afe11db16aef6fd8cf2a5de380/href
Within the above instance, after the consumer clicks on the web page, the textual content within the clipboard can be output. Notice that the browser will pop up a dialog field presently, asking the consumer whether or not to agree with the script to learn the clipboard.
If the consumer disagrees, the script will report an error. Presently, you should use the attempt…catch construction to deal with errors.
https://medium.com/media/7c30cda146134fe78fac02686240a822/href
clipboard.learn()
The clipboard.learn() methodology is used to repeat the information within the clipboard, which might be textual content knowledge or binary knowledge (corresponding to footage). This methodology requires express permission from the consumer. This methodology returns a Promise object. As soon as the state of the thing turns into resolved, an array might be obtained, and every array member is an occasion of a ClipboardItem object.
https://medium.com/media/5cfc2aab31a340fb24537d54448883e5/href
The ClipboardItem object represents a single clip merchandise and every clip merchandise has a clipboardItem.sorts property and a clipboardItem.getType() methodology. The clipboardItem.sorts property returns an array whose members are the MIME sorts obtainable for the clip merchandise. For instance, a clip merchandise might be pasted in HTML format or in plain textual content format. Then it has two MIME sorts (textual content/html and textual content/plain). The clipboardItem.getType(kind) methodology is used to learn the information of the clip merchandise and returns a Promise object. This methodology accepts the MIME kind of the clip merchandise as a parameter and returns the information of that kind. This parameter is required, in any other case, an error can be reported.
clipboard.writeText()
The clipboard.writeText() methodology is used to jot down textual content content material to the clipboard.
https://medium.com/media/b2786f780145c34da1d8d8b5f9970b7a/href
The above instance is that after the consumer clicks on the net web page, the script writes textual content knowledge to the clipboard. This methodology doesn’t require consumer permission, however it’s best to place it in attempt…catch to stop errors.
https://medium.com/media/5b8e90947eaf99a062e9f43615c2fb1d/href
clipboard.write()
The clipboard.write() methodology is used to jot down arbitrary knowledge to the clipboard, which might be textual content knowledge or binary knowledge. This methodology accepts a ClipboardItem occasion as a parameter, which represents the information written to the clipboard.
https://medium.com/media/1e4d8b9a0faa7aa9e8a6e4b84bd23a91/href
Within the above instance, the script writes an image to the clipboard. Notice that the Chrome browser presently (till this author writes this text) solely helps writing photos in PNG format. clipboardItem() is a constructor natively offered by the browser to generate an occasion of clipboardItem. It accepts an object as a parameter. The important thing title of the thing is the MIME kind of the information, and the important thing worth is the information itself. The next instance is to jot down the worth of the identical clip merchandise in a number of codecs to the clipboard, one is textual content knowledge, and the opposite is binary knowledge for pasting on completely different events.
https://medium.com/media/4f89456ef61ba1676c74565508e34724/href
Copy, Lower, and Paste Occasions
When the consumer places knowledge into the clipboard, the copy occasion can be triggered. The next instance is to transform the textual content that the consumer places on the clipboard to uppercase.
https://medium.com/media/56349f2db4f9a0c68d50bfbd1e7b8e7d/href
Within the above instance, the clipboardData property of the occasion object comprises the clipboard knowledge. It’s an object with the next properties and strategies.
- Occasion.clipboardData.setData(kind, knowledge) : To change the clipboard knowledge, you could specify the information kind.
- Occasion.clipboardData.getData(kind) : To acquire clipboard knowledge, you could specify the information kind.
- Occasion.clipboardData.clearData([type]) : Clear clipboard knowledge, you possibly can specify the information kind. If you don’t specify the sort, all varieties of knowledge can be cleared.
- Occasion.clipboardData.gadgets : An array-like object comprises all clip gadgets, however normally there is just one clip merchandise
The next instance is to intercept the consumer’s copy operation and put the desired content material into the clipboard.
https://medium.com/media/4c39a1a4f6b3efcf4b47960f1f287627/href
Within the above instance, first, use e.preventDefault() to cancel the default operation of the clipboard, after which the script takes over the copy operation. The lower occasion is triggered when the consumer performs a reducing operation. Its processing is strictly the identical because the copy occasion, and the lower knowledge can also be obtained from the Occasion.clipboardData property.
When the consumer makes use of the clipboard knowledge to stick, the paste occasion can be triggered. The next instance is to intercept the paste operation, the information within the clipboard is taken out by the script.
https://medium.com/media/6aab8e207fccce5d7e966d382c2050b0/href
Conclusion
For consumer expertise, Clipboard entry is a superb instrument. However Clipboard entry has its thorns. Some customers convey malicious knowledge and a few customers carry delicate knowledge. Ensure you deal with different consumer’s knowledge responsibly. It’s good to put together your self for these nasty paste occasions.
Asynchronous Clipboard API is new, and no browser helps all options, but it surely’s simpler to make use of and extra sturdy than the outdated Doc.execCommand() methodology.
Discover Clipboard Operation in JavaScript was initially printed in Geek Tradition on Medium, the place individuals are persevering with the dialog by highlighting and responding to this story.

