-2

I'm looking for a suitable way to copy URL (link) to the clipboard.

Can someone tell me how this can be achieved?

function copyURL() {      
  var elem = document.createElement("textarea");      
  document.body.appendChild(elem);      
  elem.value = google.com;      
  elem.select();      
  document.execCommand("copy");      
  document.body.removeChild(elem);      
  document.write("Copied to clipboard!");
}
<a href="javascript:void(1);" onclick="copyURL()">Copy URL</a>
BillNathan
  • 589
  • 1
  • 6
  • 26
  • A more detailed question with your requirements would allow others to help you a little more - for example, include your comments (that you wrote on answers below) about it needing to be 'on click', needing a success message, etc. – coops May 30 '19 at 12:56

3 Answers3

0

You can use

document.execCommand("copy");

Fiddle: Fiddle

Paulo Campez
  • 702
  • 1
  • 8
  • 24
0

You can use window.location.href and .execCommand on a hidden textarea:

var url = document.getElementById('url')
url.value = location.href
url.select()
document.execCommand("copy");
Not hidden for example:<br>
<textarea id="url"></textarea>
Kobe
  • 6,226
  • 1
  • 14
  • 35
0

Try making a dummy input, copying it, then removing it.

function copyURL() {      
  var elem = document.createElement("textarea");      
  document.body.appendChild(elem);      
  elem.value = location.href;      
  elem.select();      
  document.execCommand("copy");      
  document.body.removeChild(elem);      
  document.write("Copied to clipboard!");
}
<button onclick="copyURL()">Copy URL</button>
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79