š This post mentions Glitch, which has now shut down. Check my After Glitch page.
Copy HTML with native Clipboard API
The relatively new Clipboard API in browsers lets you load up the userās clipboard as though theyād copied something themselves. Doing so with text or images is fairly well documented, but writing rich text (as HTML) is harder to come by.
At time of writing, itās implemented in Chrome 86+ and in Safari. I got the content for this post from the Glitch project created by dsleeps at Google.
How to copy rich text HTML onto the Clipboard API
This sample assumes you have a `<div class="js-output"></div>ā containing your HTML to copy.
Iāll cut right to it:
try {
const content = document.getElementsByClassName('js-output')[0].innerHTML;
const blobInput = new Blob([content], {type: 'text/html'});
const clipboardItemInput = new ClipboardItem({'text/html' : blobInput});
navigator.clipboard.write([clipboardItemInput]);
} catch(e) {
// Handle error with user feedback - "Copy failed!" kind of thing
console.log(e);
}
Key things:
- Get the HTML string (Iām using
innerHTMLof an element for this) - Create a new
Blob. - Create a
ClipboardItemaround the blob, specifying MIME type again - Finally, write the
ClipboardItemto the clipboard API.
Demo
I have a quickly-made Vue app with a āCopy to Clipboardā button at https://stegriff.github.io/deployment-complete/. Source repo at https://github.com/stegriff/deployment-complete.
Hoping this tutorial helps you!