Toolsnip

Javascript: Copy Text to Clipboard

Learn how to copy text to the clipboard using JavaScript. This snippet demonstrates using the Clipboard API to write text to the clipboard, providing a simple and secure way to copy information.

Copying text to the clipboard is a common feature in web applications, allowing users to quickly copy and share information. This snippet demonstrates how to copy text to the clipboard using the Clipboard API in JavaScript. The Clipboard API provides a simple and secure way to interact with the clipboard, enabling web applications to read and write clipboard contents.

In this example, we define a function copyToClipboard that takes a text string as an argument. The function uses the navigator.clipboard.writeText method to write the text to the clipboard. This method returns a promise that resolves when the text is successfully copied. To provide feedback to the user, the function logs a success message to the console.

The Clipboard API is part of the modern JavaScript standard and is supported in most modern browsers. It offers a more reliable and secure way to interact with the clipboard compared to older methods such as using hidden text areas and the document.execCommand method. The Clipboard API ensures that clipboard operations are performed with user consent and in a secure context.

Copying text to the clipboard is useful in various scenarios, such as sharing URLs, copying codes or passwords, and more. Understanding how to use the Clipboard API can help you implement this feature efficiently and securely in your applications.

The Clipboard API provides additional methods for reading from and writing to the clipboard, allowing for more advanced clipboard interactions. By leveraging these features, you can enhance the usability and functionality of your web applications.

Snippet Code

Use Cases

  • Sharing URLs
  • Copying codes or passwords
  • Providing quick copy features
  • Enhancing user experience
  • Implementing clipboard interactions