Skip to content

Instantly share code, notes, and snippets.

@stevebauman
Last active October 12, 2021 11:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stevebauman/82b97abbb9e58e477386f8e42f900800 to your computer and use it in GitHub Desktop.
Save stevebauman/82b97abbb9e58e477386f8e42f900800 to your computer and use it in GitHub Desktop.
Copy Rich Text to Clipboard Cross Platform & Browser
/**
* 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