How to copy HTML to clipboard
Copy text as HTML without framework. Just plain JavaScript.
Published: May 7, 2022 Sponsored App StoreI recently needed to copy HTML into user’s clipboard that would then be pasted into an email. Mostly because of some very basic formatting and hyperlinks.
Copying HTML that gets correctly pasted elsewhere is now thankfully pretty straightforward thanks to the ClipboardItem
. You can create instance and then write it to the clipboard.
There is a smaller issue and that is missing Firefox support as of May 7. Since this is available under flag since end of last year, I expect support in the coming months.
Because this feature is not critical, I am just showing an alert to Firefox users explaining that their browser isn’t supported.
With that out of the way, here is the code:
const copyContentButton = document.getElementById("copyContentButton");
copyContentButton.addEventListener('click', () => {
if(typeof ClipboardItem === "undefined") {
alert("Sorry! This feature is not yet available in the browser you are using.\n\n" +
"Selecting the text and pasting it to your email should give you the same result.")
return;
}
const type = "text/html";
const blob = new Blob([exampleContent.innerHTML], {type});
const data = [new ClipboardItem({[type]: blob})];
navigator.clipboard.write(data).then(function () {
exampleContent.style.opacity = '0.4';
setTimeout(function () {
exampleContent.style.opacity = '1';
}, 80)
}, function () {
// Fallback in case the copy did not work
});
});
Most of the code above is standard JavaScript. The relevant code is creating the Blob
and then ClipboardItem
and finally using the navigator
API to write the content.
I am using the opacity
changes to flash the content which gets copied to provide feedback to the user.