How do I copy to the clipboard in JavaScript?
The standard practice to copy text in JavaScript involves the navigator.clipboard.writeText(text) method. Execution of this method should occur during an event like onclick:
Remember, this only works within user-initiated events due to security reasons.
Step-by-step breakdown
- 
User actions activation: Pasting to the clipboard necessitates user actions such as clicks or keypresses to satisfy current web security standards. 
- 
Using navigator.clipboard.writeText: This asynchronous function is the optimal choice for copying plain text. It's worth noting that this must be used in a secure context—most modern browsers support this method if served over HTTPS. Do keep in mind to avoid it being blocked on the main thread.
- 
Fallback approach — document.execCommand('copy'): Whennavigator.clipboardisn't available (perhaps on older browsers or HTTP sites), consider using the crusty, but reliabledocument.execCommand('copy'). This method is deprecated, and can behave sporadically—use with care!
Tackling the unknowns — Edge and IE
From the frontline of cross-browser compatibility, comes our next move. Dealing with Internet Explorer (IE) requires addressing its idiosyncrasies—like invoking the createTextRange method:
In the realm of Microsoft Edge, to prevent a sudden leap to the bottom when a hidden textarea is focused, you can outsmart it by shoving its position off-screen:
Lastly, proactively checking feature availability with document.queryCommandSupported('copy') helps confirm your copying superpowers before embarking on the operation.
Advanced clipboard — copying rich content
When you want to impress your date by coping more than just plain text—maybe a multilayered rich text or images, your sure-shot trick is to follow the broad instructions outlined in the Clipboard API's copy event:
Remember, manual handling of events and DataTransfer objects would need more knowledge under the hood. But hey, the control you gain is absolute!
User interface - Putting 'em in control
Make all your clipboard instructions user-centric. The user should captain the ship—initiating the copy action in most cases, preferably via a dedicated button or link. Throw in a confirmation of a successful copying to reassure your users:
This savvy function prompts the user to copy the text manually when the programmatic approach nose-dives, ensuring that functionality always wins over API tantrums.
Was this article helpful?
