Why am I unable to copy text to the clipboard using the Clipboard API?

I'm trying to make an HTML element where, when clicked, copies some text to the clipboard. I was originally using the Clipboard API, but it doesn't work.
Does anybody know how I can do a similar thing that would work on all modern browsers (assuming they are fully up to date)? It's for a website of mine, and I want it to copy my email when clicked. It could be a button, link, whatever.
I tried using a button that ran a JS function called copyText(text)
, but nothing actually got copied.
function copyText(text) {
navigator.clipboard.writeText(text)
console.log("${text} copied successfully!")
}
When I ran the above code using <button onclick="copyText(copy)" target="_blank">copy</button>
, I get this error (in Chrome):
Uncaught ReferenceError: copy is not defined
at HTMLButtonElement.onclick (linkWork.html:16:63)
Answer
The problem has nothing to do with the clipboard API. There is an error in your script code, as pointed out by the browser's error message:
Uncaught ReferenceError: copy is not defined
The problem is here:
<button onclick="copyText(copy)" target="_blank">copy</button>
^^^^
copyText()
is expecting you to pass in a value, but copy
is not previously declared anywhere.
In this case, try simply passing in a string literal instead:
<button onclick="copyText('copy')" target="_blank">copy</button>
And since your goal is to copy an email, then you should actually try doing that, eg:
<button onclick="copyText('[email protected]')" target="_blank">copy</button>
Enjoyed this question?
Check out more content on our blog or follow us on social media.
Browse more questions