11

I've been wondering how to copy a link with its HREF and text, for example we have an tag like this:

<a href="http://mysite.sample/?creds=creds">Quick Access to the website</a>

So basically I perfectly know how to copy something into the clipboard, my current work around consists in creating an invisible and small textarea where I put the text what I want to copy, then I select with js all the text inside the textarea and exec the copy command like this:

document.execCommand('copy');

Alright so I am able to copy raw text without issues, I can copy a link into my clipboard but once I paste it the link is just text and not an active link which can be clicked to go to its destination.

I know why is this happening, once I put the link into the textarea then it is not a link anymore but I don't know any other way to do this without breaking the link.

So, Once I copy the link I don't need to modify it with js or change the href or whatever, once I copy the link I want to paste it in a different page where I have no control over and I want my link to still be a link and not a simple text.

Any help would be appreciated. Due the project I'm working on I cannot relay on libraries for doing this I need some kind of native js workaround

This post is different to the post of How do I copy to the clipboard in JavaScript? I already know how to do that. What I want to know is how is posible to copy a link without losing it's link properties.

Osakr
  • 1,027
  • 1
  • 13
  • 26
  • When you are copying a link, is it returning the full `Link Name` or is it just returning the source/`href`? – Lewis Browne Oct 26 '18 at 07:56
  • It returns the full text with the href and the tag itself but is not a clickable resource, it is just text and I want it to keep its link properties – Osakr Oct 26 '18 at 07:58
  • I don't understand the question. Where are you pasting the link again? The clipboard has no idea what a hyperlink is, its just text. So you'll have to paste the entire tag into something that understands HTML syntax. Or paste the url alone into something that can detect urls, like an email. So we need to know Where you're pasting the link to know what you should paste. – Shilly Oct 26 '18 at 07:58
  • Basically if I have a link somewhere and I manually copy it with right click then when I paste it, for example in a email in gmail, it will be pasted as a link so after I paste it I can keep clicking on the link. I want to do that but in javascript – Osakr Oct 26 '18 at 08:00
  • Hello @ThisGuyHasTwoThumbs would you mean to read the full post?? I do know how to copy with javascript but Im asking how to copy a LINK without losing its link properties – Osakr Oct 26 '18 at 08:02
  • @Osakr when you are copying the element using `js` what are you then pasting into? – Lewis Browne Oct 26 '18 at 08:02
  • @Osakr the principle is still the same, get the `attr('href')` (jQuery I know - I don't know vanilla JS) and then store that to a string, then use window.location.href to change to it, or just use it elsewhere ... – treyBake Oct 26 '18 at 08:03
  • Let's say I will paste into a email in gmail for example, I want to once I paste the link I'm able to click and go to it's href – Osakr Oct 26 '18 at 08:03
  • @Osakr then take the url and build html using JS and output to the email ... – treyBake Oct 26 '18 at 08:04
  • @Osakr that's a setting in your gmail that detects the string you paste is an URL. My gmail does not do that, I have to manually mark the string as a link. Same with like word, where you have to press enter for word to detect its an url. just pasting a string won't automatically make it an url without pressing enter. – Shilly Oct 26 '18 at 08:04
  • So as ThisGuy states, your best bet is to create a html page containing the link and use that as the email body so it'll act like a web page. – Shilly Oct 26 '18 at 08:05
  • So basically what I need to do is to generate a link which give me the chance to login into a web application without need to give my credentials. So, once the link is generated it has many parameters encrypted and at the end is a really long href. Then I have a button which copies the link into my clipboard to send it by email to a regular user, the link is successfully copied into my clipboard but once I paste it in gmail or whatever page the link doesn't show the text with the underline and if I click then brings me to the href, it pastes the whole tag and its href is visible. – Osakr Oct 26 '18 at 08:10
  • You can't modify GMAIL behaviour - that would be a huge security flaw in any email client. You should build a HTML email that sends to the user for them to click on ... – treyBake Oct 26 '18 at 08:14
  • Well Gmail was just an example, doesn't matter where do I paste my link, it is not a link anymore once I copy it – Osakr Oct 26 '18 at 08:15
  • @ThisGuyHasTwoThumbs is right, if you are wanting to put it into an email then you will need to generate a `HTML` email to send valid `HTML` code. A plain-text email not render the elements as you would expect. – Lewis Browne Oct 26 '18 at 08:16
  • For those of you who said that It was not posible, please check the answer of @Amadan . – Osakr Oct 26 '18 at 08:20
  • 3
    @Shilly: "The clipboard has no idea what a hyperlink is, its just text." This is incorrect. A clipboard (on all the major OS platforms) can hold a variety of content types, and carries the information of the type with it. Otherwise it would not be possible to copy-paste e.g. images, or formatted MS Word paragraphs, or files from one folder to another. Copying HTML is not a problem; though obviously the application that is accepting the paste must know how to handle the pasted type, and agree it's a valid operation (e.g. pasting a PNG into Notepad won't work). – Amadan Oct 26 '18 at 10:44
  • Duplicate of [this question](https://stackoverflow.com/questions/400212/how-do-i-copy-to-the-clipboard-in-javascript). – webtweakers May 30 '20 at 17:09

2 Answers2

15

A <textarea> can only contain text. You need to copy an actual link. Try this:

const onClick = evt => {
  const link = document.querySelector('a');
  const range = document.createRange();
  range.selectNode(link);
  const selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);

  const successful = document.execCommand('copy');
};

document.querySelector('button').addEventListener('click', onClick);
This is an <a href="https://example.com">Example</a>.

<button>Copy</button>

EDIT: I noticed that I missed a huge discussion about... email? but I answered the question as asked - how to copy an actual link to clipboard.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • 1
    So much thanks you! Everybody was saying that i wasn't posible but you just showed how 'easy' you solve my question! You have my respect. I tried it and works perfect when I paste the link into gmail or any other page – Osakr Oct 26 '18 at 08:18
  • I just tried your solution in my application and works really well. Thanks so much, I've never used the createRange() so I really appreciate your answer – Osakr Oct 26 '18 at 09:01
  • 2
    Thanks been searching for hours for this. – Worthy7 Nov 06 '19 at 06:55
  • Great Answer, I think this only works over HTTPS??? – cwmacken Jul 17 '20 at 04:24
  • 1
    @cwmacken I'm not sure, this was long time ago and don't remember well but i think i used this with HTTP – Osakr Jul 26 '20 at 20:05
  • @Osakr cool thanks for the heads up... def possible that browsers have updated this since 2018. – cwmacken Sep 15 '20 at 17:58
2

Here is another approach using the Clipboard interface (with step by step comments).

// Get the html from the portion of the page to copy (in this specific case your link)
const HTML=document.querySelector("a").outerHTML;

// Create a blob from the html
const TYPE="text/html";
const BLOB=new Blob([HTML], {type:TYPE});

// Copy the blob to the clipboard
navigator.clipboard.write([new ClipboardItem({[TYPE]: BLOB})])

// Optional but recommended. Check the result of the async operation
.then(
  ()=>console.log("copied"),
  (err)=>console.log(err)
);

Please notice that the const HTML can be extracted from the document, as well as created on the fly. So you might do something like:

const HTML="<a href='http://mysite.sample/?creds=creds'>Quick Access to the website</a>";
Lux
  • 71
  • 4