Skip to content

JavaScript copy to clipboard

  • by

Copying text to the clipboard using JavaScript can be achieved with the navigator.clipboard.writeText() method, which is supported in most modern browsers.

const textToCopy = "Hello, world!"; // replace with your text
navigator.clipboard.writeText(textToCopy)
  .then(() => {
    console.log("Text copied to clipboard");
  })
  .catch((error) => {
    console.error("Could not copy text: ", error);
  });

This method returns a Promise that resolves when the text has been successfully copied to the clipboard and rejects if there was an error.

Note: this method may not work if clipboard access is disabled in the browser or if the page is not running in a secure context.

JavaScript Copy to clipboard example

Simple example code that demonstrates how to copy a string to the clipboard using JavaScript with an HTML button.

<!DOCTYPE html>
<html>
<head>
  <title>Copy to Clipboard</title>
</head>
<body>
  <input type="text" id="myInput">
  <button onclick="copyText()">Copy to clipboard</button>

  <script>
    function copyText() {
      const inputElement = document.getElementById('myInput');
      const textToCopy = inputElement.value;
      navigator.clipboard.writeText(textToCopy)
        .then(() => {
          console.log(`Copied "${textToCopy}" to clipboard`);
        })
        .catch((err) => {
          console.error('Could not copy text: ', err);
        });
    }
  </script>
</body>
</html>

Output:

JavaScript copy to clipboard

This code defines an input field with the ID “myInput” and a button with an onclick attribute that calls the copyText() function.

The copyText() function retrieves the text to copy from the input field using document.getElementById('myInput').value, and then calls the navigator.clipboard.writeText() method with the text to copy.

Do comment if you have any doubts or suggestions on this Js basic topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading