0

I want to be able to have the user click a button and have javascript copy some certain text into their clipboard. I was able to get this to work using a , where any value they put in would be copied, but is there any way I can do it with just a and some ?

I tried the following:

<html>
<head>
<title>
</title>
</head>
<body>
<button id='myBtn' onclick='myFunction()'>Click Me</button>
</body>
<script>
function myFunction() {
  var copyText = 'CopiedText';
  copyText.select();
  copyText.setSelectionRange(0, 99999)
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
</script>
</html>
Coolsugar
  • 55
  • 6
  • 2
    Does [this](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) answer your question? – em0lar Dec 05 '20 at 09:17

2 Answers2

0

you can see w3c document right here. here's the example

<html>

<head>
    <title>
    </title>
</head>

<body>
    <button id='myBtn' onclick='myFunction()'>Click Me</button>
    <textarea></textarea>
</body>
<script>
    async function myFunction() {
        var copyText = 'CopiedText22';
        var data = [new ClipboardItem({ "text/plain": new Blob([copyText], { type: "text/plain" }) })];
        await navigator.clipboard.write(data);
        alert(`Copied the text: ${copyText} successfully copied`);

    }
</script>

</html>

and then you can paste the result to textarea

0
  1. The execCommand('copy') API isn't supported in Safari and in some version of chrome or mozila.
  2. Try to use the command below to copy or write text on clipboard.
  3. call this function on button click.
  4. For more info refer : https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard

   private copyToClipboard =  async (textToCopy: string) => {
      await navigator.clipboard.writeText(textToCopy);
   };

whistler
  • 1
  • 1