Skip to content

Instantly share code, notes, and snippets.

@eprev
Created February 7, 2017 09:48
Show Gist options
  • Save eprev/79290a497fa22e700c42e27a3e26566e to your computer and use it in GitHub Desktop.
Save eprev/79290a497fa22e700c42e27a3e26566e to your computer and use it in GitHub Desktop.
// Usage: copyToClipboard('Hello');
const copyToClipboard = (function(){
let textToCopy;
let clearSelection = false;
let didCopy = false;
document.addEventListener('copy', e => {
if (textToCopy !== undefined) {
try {
e.clipboardData.setData('text/plain', textToCopy);
e.preventDefault();
didCopy = true;
} finally {
textToCopy = undefined;
}
}
});
return function(text) {
textToCopy = text;
if (!document.queryCommandEnabled('copy')) {
// See: https://bugs.webkit.org/show_bug.cgi?id=156529
const sel = document.getSelection();
const range = document.createRange();
range.selectNodeContents(document.body);
sel.addRange(range);
clearSelection = true;
}
didCopy = false;
document.execCommand('copy');
if (clearSelection) {
clearSelection = false;
document.getSelection().removeAllRanges();
}
return didCopy;
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment