Created
December 4, 2024 12:21
-
-
Save maztch/52ae89af778f37001850030869b06ebc to your computer and use it in GitHub Desktop.
Javascript copy rich text format and raw at once
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function copyToClip(elementId) { | |
const rich = document.getElementById(elementId).innerHTML | |
const plain = document.getElementById(elementId).innerText | |
if (typeof ClipboardItem !== "undefined") { | |
const html = new Blob([rich], { type: "text/html" }); | |
const text = new Blob([plain], { type: "text/plain" }); | |
const data = new ClipboardItem({ "text/html": html, "text/plain": text }); | |
await navigator.clipboard.write([data]); | |
} else { | |
const cb = e => { | |
e.clipboardData.setData("text/html", rich); | |
e.clipboardData.setData("text/plain", plain); | |
e.preventDefault(); | |
}; | |
document.addEventListener("copy", cb); | |
document.execCommand("copy"); | |
document.removeEventListener("copy", cb); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment