When I copy a browser tab URL, I often want to also keep the title. Sometimes I want to use the link as rich text (e.g., when pasting the link into OneNote or Jira). Sometimes I prefer a Markdown link. There are browser extensions to achieve this task, but I don't want to introduce potential security issues. Instead, I've written a bookmarklet based on this example extension.
To use it, drag the following link onto your browser bookmarks bar:
When you click the bookmark(let), the current page including its title will be copied into your clipboard. You don't even have to choose the output format: the link is copied both as rich text and plain text (Markdown). This works because it's possible to write multiple values into the clipboard with different content types.
Here's the source code:
function escapeHTML(str) {
return String(str)
.replace(/&/g, "&")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/</g, "<")
.replace(/>/g, ">");
}
function copyToClipboard({ url, title }) {
function onCopy(event) {
document.removeEventListener("copy", onCopy, true);
// hide the event from the page to prevent tampering
event.stopImmediatePropagation();
event.preventDefault();
const linkAsMarkdown = </span><span class="token string">[</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>title<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">](</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>url<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">)</span><span class="token template-punctuation string">
;
event.clipboardData.setData("text/plain", linkAsMarkdown);
const linkAsHtml = </span><span class="token string"><a href="</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span><span class="token function">escapeHTML</span><span class="token punctuation">(</span>url<span class="token punctuation">)</span><span class="token interpolation-punctuation punctuation">}</span></span><span class="token string">"></span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">${</span>title<span class="token interpolation-punctuation punctuation">}</span></span><span class="token string"></a></span><span class="token template-punctuation string">
event.clipboardData.setData("text/html", linkAsHtml);
}
document.addEventListener("copy", onCopy, true);
document.execCommand("copy");
}
copyToClipboard({ url: window.location.toString(), title: document.title });