Stefano Saitta
Stefano Saitta

Reputation: 2024

Copy to clipboard hidden element

I'm trying to understand why this code does not work.

What i'm trying to accomplish is to copy into clipboard the current url, so as a workaround i try to create an hidden input in which i pass the current location, but i have no luck.

here an example of what i've tried so far:

var copyBtn = document.querySelector('#copy_btn');

copyBtn.addEventListener('click', function () {
	var input = document.createElement('input');
  input.style.display = "none";
  input.setAttribute('value', document.location)
	document.body.appendChild(input);
  // select the contents
  input.select();
  
  document.execCommand('copy');
}, false);
<input id="copy_btn" type="button" value="copy">

Upvotes: 1

Views: 2026

Answers (1)

XCS
XCS

Reputation: 28147

You can only trigger the copy command on user action (key press, click on input, etc...).

Se more info here: https://developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=en

Imagine the security risks if you opened a site and it automatically over-written your clipboard without you doing anything.

So, you should add a button to "copy the URL to clipboard" and use document.execCommand inside the click handler of that button.

LE: I just found a similar question to yours and marked this as a duplicate.

Upvotes: 2

Related Questions