Created
February 7, 2017 09:48
-
-
Save eprev/79290a497fa22e700c42e27a3e26566e to your computer and use it in GitHub Desktop.
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
// 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