CoreUI ONE — 250+ PRO components and 25+ admin templates for React, Angular, Vue, Bootstrap and Next.js, plus Data Grid, Scheduler, 4,300+ PRO icons and the Next.js boilerplate. One license. → See what you get

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, 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.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
JavaScript printf equivalent
JavaScript printf equivalent

How to Open All Links in New Tab Using JavaScript
How to Open All Links in New Tab Using JavaScript

How to Remove Underline from Link in CSS
How to Remove Underline from Link in CSS

Understanding and Resolving the “React Must Be in Scope When Using JSX
Understanding and Resolving the “React Must Be in Scope When Using JSX