1

I would like to have a specific string copied to the clipboard when clicking on a button. I do not want the string to be defined by the user (i.e. a text box or the like), but rather I want it to be defined in the code.

What I have is the following:

function yyy(){
    var dummyContent = "this is to be copied to clipboard";
    dummyContent.select();
    document.execCommand('copy')
}

<input type="button" value="foobar" onclick=yyy(); />

A solution that works but only with a text box is the following:

function Copy()
{
    var Url = document.getElementById("paste-box");
    Url.value = "this is to be copied to clipboard";
    Url.select();
    document.execCommand("Copy");
}

<input type="button" value="Copy Link" onclick=Copy(); />

I would like the string "this is to be copied to clipboard" to be copied in the clipboard.

For the first one, nothing happens. For the second, it works but again there is a text box in the code.

Kosmonaut
  • 128
  • 10
  • This won't work because dummyContent is a string, not a DOM element. Strings don't have a `select` method. – schu34 Jan 09 '19 at 17:19
  • 1
    Possible duplicate of [Copy output of a JavaScript variable to the clipboard](https://stackoverflow.com/questions/33855641/copy-output-of-a-javascript-variable-to-the-clipboard) – PM 77-1 Jan 09 '19 at 17:19
  • Create a dummy input, set the value, copy content, delete the element. Easy peasy. – basic Jan 09 '19 at 17:22

1 Answers1

1

You can use the Clipboard api in the browser to accomplish this, but note that it's not supported in many browsers yet.

Example code:

Clipboard.writeText("this is in my clipboard").then(()=>console.log("successfully copied string"))

Clipboard docs: https://developer.mozilla.org/en-US/docs/Web/API/Clipboard

schu34
  • 965
  • 7
  • 25