Skip to content

Instantly share code, notes, and snippets.

@tonitrnel
Last active June 14, 2020 23:20
Show Gist options
  • Save tonitrnel/14c901f5f039f955c28e80cd1146b7ea to your computer and use it in GitHub Desktop.
Save tonitrnel/14c901f5f039f955c28e80cd1146b7ea to your computer and use it in GitHub Desktop.
clipboard
export const copy = (text: string) => {
if (!navigator.clipboard) {
return fallback(text)
}
return navigator.clipboard.writeText(text)
}
/**
* fallback
* @param text
*/
const fallback = async (text: string) => {
return new Promise<void>((resolve, reject) => {
const el = document.createElement('textarea')
el.value = text
el.style.top = '0'
el.style.left = '0'
el.style.position = 'absolute'
el.style.opacity = '0'
el.style.zIndex = '-2'
document.body.appendChild(el)
el.focus()
el.select()
const successful = document.execCommand('copy')
successful ? resolve() : reject(new Error('Fallback: Copying text command was unsuccessful'))
document.body.removeChild(el)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment