Search code examples
javascripthtmlclipboard

Copy the text to the Clipboard without using any input


I just saw many articles in the web to find a solution to copy text to the Clipboard. But Every tutorials explain with inputs examples.

  function GeeksForGeeks() {
            var copyGfGText = document.getElementById("GfGInput");
            copyGfGText.select();

            document.execCommand("copy");

            alert("Copied the text: " + copyGfGText.value);
          }
  <input type="text" value="GeeksForGeeks" id="GfGInput">

         <!-- The button used to copy the text -->
         <button onclick="GeeksForGeeks()">Copy text</button>

But I need to copy just a simple text. Is there a way to copy simple string from variable to the Clipboard? example`

let text = "copy this text to the clipboard";

Solution

  • You should be able to do this with document.createElement(); like this;

    function CopyMe(TextToCopy) {
      var TempText = document.createElement("input");
      TempText.value = TextToCopy;
      document.body.appendChild(TempText);
      TempText.select();
      
      document.execCommand("copy");
      document.body.removeChild(TempText);
      
      alert("Copied the text: " + TempText.value);
    }
    <button onclick="CopyMe('The text here will be copied')">Copy text</button>

    Let me know how this helps.

    =============== UPDATE - March 2023 ===========

    The execCommand method may not be available in all browsers so a better way to do this now would be;

    function copyToClipboard(text) {
      navigator.clipboard.writeText(text)
    .then(() => {
      console.log(`Copied text to clipboard: ${text}`);
      alert(`Copied text to clipboard: ${text}`);
    })
    .catch((error) => {
      console.error(`Could not copy text: ${error}`);
    });
    }
    <button onclick="copyToClipboard('The text here will be copied')">Copy text</button>

    This is a better and cleaner way to do same thing but if the website you're working on has a Content Security Policy (CSP) or other security settings that prevent access to the clipboard you will get errors (https://sites.google.com/a/chromium.org/dev/Home/chromium-security/deprecating-permissions-in-cross-origin-iframes).