0

I need to copy the URL title so I can save it without manually selecting it and then copying, so I wonder if is it possible to copy the window title to the clipboard?

I have tried with the following script with no luck :

<script>
function myFunction() {
  var copyText = This.document.title;
  copyText.select();
  document.execCommand("copy");
  alert("Copied the text: " + copyText.value);
}
</script>

Any help would be appreciated, thanks in advance.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • Possible duplicate of [Copy text string on click](https://stackoverflow.com/questions/45071353/copy-text-string-on-click) – prasanth May 12 '19 at 13:16
  • 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) – Nick Parsons May 12 '19 at 13:17

1 Answers1

2

Make a temporary textarea element - also note it needs the button click to work:

function myFunction() {
  var copyText = window.location.href;
  var elem = document.createElement("textarea");
  document.body.appendChild(elem);
  elem.value = copyText;
  elem.select();
  document.execCommand("copy");
  document.body.removeChild(elem);
}
<button onclick="myFunction()">Click</button>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79