How to copy URL on button click?
No need to create new textarea
. try to get existing textarea
by giving some id
('url').
Here is the working example
function Copy() {
var Url = document.getElementById("url");
Url.innerHTML = window.location.href;
console.log(Url.innerHTML)
Url.select();
document.execCommand("copy");
}
<div>
<input type="button" value="Copy Url" onclick="Copy();" />
<br /> Paste: <textarea id="url" rows="1" cols="30"></textarea>
</div>
You should not use execCommand
anymore, is deprecated, use the Clipboard
API:
let url = document.location.href
navigator.clipboard.writeText(url).then(function() {
console.log('Copied!');
}, function() {
console.log('Copy error')
});
More on it: https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API