Last active
October 12, 2021 11:02
-
-
Save stevebauman/82b97abbb9e58e477386f8e42f900800 to your computer and use it in GitHub Desktop.
Copy Rich Text to Clipboard Cross Platform & Browser
This file contains 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
/** | |
* Copy rich text content to clipboard. | |
* | |
* Must be initiated by a user click event. | |
* | |
* @param {string} content | |
*/ | |
export default function (content) { | |
const selection = window.getSelection(); | |
const range = document.createRange(); | |
range.selectNodeContents(document.body); | |
selection.removeAllRanges(); | |
selection.addRange(range); | |
const listener = (e) => { | |
e.clipboardData.setData("text/html", content); | |
e.clipboardData.setData("text/plain", content); | |
e.preventDefault(); | |
} | |
document.addEventListener("copy", listener); | |
document.execCommand("copy"); | |
document.removeEventListener("copy", listener); | |
selection.removeAllRanges(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment