How to copy text to clipboard in JavaScript
Copying text to the clipboard is a common feature in modern web applications, from “copy code” buttons to sharing links.
As the creator of CoreUI with over 25 years of JavaScript development experience, I’ve implemented this functionality in numerous production components.
The modern and most reliable solution is to use the Clipboard API with navigator.clipboard.writeText().
This method is asynchronous, secure, and works seamlessly across all modern browsers.
Use navigator.clipboard.writeText() to copy text to the clipboard.
navigator.clipboard.writeText('Hello, World!')
.then(() => console.log('Text copied'))
.catch(err => console.error('Failed to copy:', err))
The Clipboard API provides a secure way to interact with the system clipboard. The writeText() method takes a string as an argument and returns a Promise that resolves when the text is successfully copied. This asynchronous approach ensures the operation doesn’t block the main thread and allows you to handle success and error cases appropriately.
Best Practice Note
This is the same reliable method we use in CoreUI documentation and code examples for copy-to-clipboard functionality. Note that for security reasons, this API requires HTTPS in production and only works when the page has focus. For older browsers, you may need a fallback using document.execCommand('copy'), but the Clipboard API is now supported in all modern browsers.



