5

I'm trying to create a link that users can click on it, and then the href itself will be copied to the clipboard. Since I'm new to JS, I couldn't do it with the information I found, because I saw examples where people would click on a button to copy the url, or it would copy the URL of the address bar.

Here is my code, and + artworkUrl + is dynamically filled.

<a id="get-app-artwork" href="' + artworkUrl + '" target="_blank">Copy the cover URL</a>

How can I make this url be copied to the clipboard on click? Every option I found uses different approaches. As I'm new to this, I don't know how to apply to this situation, where I have a link and want to copy the URL of it when clicked.

  • Possible duplicate of [How do I copy to the clipboard in JavaScript?](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript) – jmargolisvt Feb 14 '19 at 21:06
  • I want to copy the href value. That's not what the mentioned link is about. This is not an input, it is a link. – Henrique Barcelos Feb 14 '19 at 21:11
  • 1
    if you want a link to copy something on click instead of navigating somewhere on click, you probably shouldn't be using an `a` tag. Maybe use a button, or style some text to look like a link, and attach a `(click)` even handler to that element and copy the needed text to the clipboard there. – joh04667 Feb 14 '19 at 21:17
  • So you get the link and than you set the input value and than you copy it – epascarello Feb 14 '19 at 21:17

1 Answers1

7

Use the Clipboard API, specifically the writeText function.

<a href="' + artworkUrl + '" onclick="copyURI(event)">Copy cover URL</a>
function copyURI(evt) {
    evt.preventDefault();
    navigator.clipboard.writeText(evt.target.getAttribute('href')).then(() => {
      /* clipboard successfully set */
    }, () => {
      /* clipboard write failed */
    });
}

EDIT 18/07/2020 : There is a missing ) to properly close the writeText( function.

AetherUnbound
  • 1,354
  • 8
  • 9
Effective Robot
  • 206
  • 1
  • 5
  • It seems you may also need `onclick="copyURI(event)"` in the anchor tag in order for the function to be called appropriately. – AetherUnbound Jul 31 '20 at 21:04