Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy URL on button click?

I am trying to copy the current page URL in the text area on button click. Somehow I have tried but is not working. http://www.w3schools.com/code/tryit.asp?filename=FAF25LWITXR5


    function Copy() 
    {
        var Url = document.createElement("textarea");
        Url.innerHTML = window.location.href;
        Copied = Url.createTextRange();
        Copied.execCommand("Copy");
    }
<div>
 <input type="button" value="Copy Url" onclick="Copy();" />
 <br />
 Paste: <textarea rows="1" cols="30"></textarea>
</div>

like image 962
Nithya Avatar asked Dec 04 '16 12:12

Nithya


People also ask

How do you copy a click URL?

After the address is highlighted, press Ctrl + C or Command + C on the keyboard to copy it. You can also right-click any highlighted section and choose Copy from the drop-down menu. Once the address is copied, paste that address into another program by clicking a blank field and pressing Ctrl + V or Command + V .


1 Answers

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

like image 94
Mr.Web Avatar answered Sep 29 '22 12:09

Mr.Web