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.


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.
How to show or hide elements in React? A Step-by-Step Guide.
How to show or hide elements in React? A Step-by-Step Guide.

CSS Selector for Parent Element
CSS Selector for Parent Element

What is the Difference Between Null and Undefined in JavaScript
What is the Difference Between Null and Undefined in JavaScript

What is globalThis in JavaScript?
What is globalThis in JavaScript?

Answers by CoreUI Core Team