An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
July 8, 2021 03:57 pm GMT
Original Link: https://dev.to/stegriff/copy-rich-html-with-the-native-clipboard-api-5ah8
Copy rich HTML with the native Clipboard API
The relatively new Clipboard API in browsers lets you load up the users clipboard as though theyd copied something themselves.
Copying text or images is fairly well documented, but examples writing rich text (as HTML) are harder to come by.
At time of writing, this is 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>
which contains your HTML to copy.
Ill 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 (Im using
innerHTML
of an element for this) - Create a new
Blob
. - Create a
ClipboardItem
around the blob, specifying MIME type again - Finally, write the
ClipboardItem
to 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.
I hope this tutorial helps you! What will you make?
Original Link: https://dev.to/stegriff/copy-rich-html-with-the-native-clipboard-api-5ah8
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To