Skip to content

Instantly share code, notes, and snippets.

@djekl
Forked from stevebauman/clipboard.js
Created October 12, 2021 11:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djekl/f163efa095cacf41c3dc7a46b2d6938f to your computer and use it in GitHub Desktop.
Save djekl/f163efa095cacf41c3dc7a46b2d6938f 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