Problem: You want to copy a link into the clipboard from a web-app such that when you paste, you get the link URL AND the link text.

For example, I was developing a web-based IM client. I wanted users to be able to copy a link from another part of our web-app and paste it into the web client. But I didn't want them to see the full ugly URL, but rather a nice small text description.

The following code does the link URL part:

window.clipboardData.setData("Text", "http://www.google.com");

Supposedly, it can also take a "Url" value for the first parameter. However, I could not get this to work, and I'm not sure what it's supposed to do anyway.

Note: There may be no general solution for all browsers. I didn't find one, in any case.

SOLUTION FOR IE ONLY:

// create an "A" DOM object, and populate the link text and url
var linkElement = document.createElement("a");
linkElement.setAttribute("href", linkHref);
linkElement.innerHTML = linkBody;

// create an editable DIV, this is crucial because a regular DIV
//will not preserve the link URL when copying from a createTextRange
var linkSubElement = document.createElement("div");
with (linkSubElement) {
contentEditable = true;
}
linkSubElement.appendChild(linkElement);

// select the editable content and copy it
//to the clipboard (this is the IE only part)
var r = document.body.createTextRange();
r.moveToElementText(linkSubElement);
r.select();
r.execCommand("Copy");