Last active
August 26, 2018 08:07
-
-
Save myfreeer/73931ae2210030fe2b25447fd21017dd to your computer and use it in GitHub Desktop.
Copy text to clipboard
This file contains hidden or 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
'use strict'; | |
/** | |
* Copy text to clipboard | |
* @param {string | Element} text | |
* @return {boolean} | |
*/ | |
const copy = (text = '') => { | |
if (text instanceof Function) | |
text = text(); | |
let elem = text; | |
if (!(text instanceof Element)) { | |
// elem = document.createTextNode(text); | |
elem = document.createElement('textarea'); | |
elem.setAttribute('readonly', true); | |
elem.style.cssText = 'position: absolute; left: -99999em'; | |
elem.value = text; | |
document.documentElement.appendChild(elem); | |
} | |
const range = document.createRange(); | |
range.selectNode(elem); | |
const sel = window.getSelection(); | |
sel.removeAllRanges(); | |
sel.addRange(range); | |
if (elem instanceof HTMLInputElement) { | |
elem.select(); | |
} | |
try { | |
const stat = document.execCommand('copy'); | |
sel.removeAllRanges(); | |
return stat; | |
} catch (e) { | |
return false; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment