Skip to content

Instantly share code, notes, and snippets.

@maztch
Created December 4, 2024 12:21
Show Gist options
  • Save maztch/52ae89af778f37001850030869b06ebc to your computer and use it in GitHub Desktop.
Save maztch/52ae89af778f37001850030869b06ebc to your computer and use it in GitHub Desktop.
Javascript copy rich text format and raw at once
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