How to copy the text to the clipboard in JavaScript ?


There are multiple ways to copy text to the clipboard in JavaScript:

Method 1: Using the Clipboard API The Clipboard API provides a simple way to interact with the clipboard. It is supported in most modern browsers.

Example:

const textToCopy = "Hello, world!";
navigator.clipboard.writeText(textToCopy)
  .then(() => {
    console.log("Text copied to clipboard");
  })
  .catch((error) => {
    console.error("Error copying text: ", error);
  });

Method 2: Using the document.execCommand() method This method is supported in most browsers, but it is being phased out in favor of the Clipboard API.

Example:

const textToCopy = "Hello, world!";
const textarea = document.createElement("textarea");
textarea.value = textToCopy;
document.body.appendChild(textarea);
textarea.select();
document.execCommand("copy");
document.body.removeChild(textarea);
console.log("Text copied to clipboard");

Method 3: Using the Clipboard.js library This is a third-party library that provides a simple way to copy text to the clipboard. It uses the Clipboard API if available, and falls back to the document.execCommand() method if not.

Example:

const textToCopy = "Hello, world!";
const clipboard = new ClipboardJS(".btn", {
  text: function() {
    return textToCopy;
  }
});
clipboard.on("success", function() {
  console.log("Text copied to clipboard");
});
clipboard.on("error", function() {
  console.error("Error copying text");
});

Note: In all of these methods, the user must grant permission for the script to access the clipboard. This is usually done by prompting the user with a dialog box.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.