Created
May 2, 2020 09:56
-
-
Save nblackburn/852cfefc01f7525bf097656aa61ce8da to your computer and use it in GitHub Desktop.
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
const PERMISSION_WRITE = 'clipboard-write'; | |
const canUseAsyncAPI = () => { | |
return ( | |
navigator.clipboard && | |
navigator.clipboard.writeText && | |
navigator.permissions && | |
navigator.permissions.request | |
); | |
}; | |
const legacyCopy = text => { | |
return new Promise((resolve, reject) => { | |
let focusTarget = null; | |
let element = document.createElement('textarea'); | |
// Capture the original focus. | |
const focusHandler = event => { | |
focusTarget = event.originalTarget; | |
}; | |
element.value = text; | |
element.addEventListener('focus', focusHandler); | |
document.body.appendChild(element); | |
element.focus(); | |
element.select(); | |
try { | |
document.execCommand('copy'); | |
element.removeEventListener('focus', focusHandler); | |
// Restore the original focus. | |
if (focusTarget !== undefined) { | |
focusTarget.focus(); | |
} | |
resolve(); | |
} catch (e) { | |
reject(); | |
} | |
document.body.removeChild(element); | |
}); | |
}; | |
const asyncCopy = text => { | |
return new Promise((resolve, reject) => { | |
navigator.permissions | |
.request({ name: PERMISSION_WRITE }) | |
.then(() => { | |
navigator.clipboard | |
.writeText(text) | |
.then(resolve) | |
.catch(reject); | |
}) | |
.catch(reject); | |
}); | |
}; | |
const copy = text => { | |
return canUseAsyncAPI() ? asyncCopy(text) : legacyCopy(text); | |
}; | |
module.exports = copy; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment