How to copy the current URL to the clipboard in Javascript
There are times when you might want to copy the URL of the current page to the clipboard for pasting elsewhere. Assuming, its Windows browser, the long way will be Alt+D, Ctrl+A (maybe) and then Ctrl+C. Wouldn't it be good if there was a way you could simply provide a button on the screen where the user could click and then URL be automatically "uploaded" to the clipboard.
You'll have seen above the text that I provide a button to do that. I'll let you into how I do it. The cheat way is :-
(img title="Copy link to paste in document or email." height="36" width="36" src="/pictures/share/copylink.png" onclick="navigator.clipboard.writeText(window.location.href);" />
All I do is simply create an image button and the magic is in the onclick event. In modern browsers there is now a Javascript command that will allow you to copy to the clipboard. You'll notice that I've done a curly bracket rather than a less than sign, its only because if I do a Less than sign, it won't show the html but a picture instead. Its only done that for demonstration otherwise an image will appear rather than code.
Tags - Javascript
Last Modified : June 2023