Created
June 24, 2021 08:53
-
-
Save steveruizok/d27d64391d0a66bcef19ca69486d2bd9 to your computer and use it in GitHub Desktop.
Copy string 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
/** | |
* Copy a string to the clipboard. | |
* @param string | |
*/ | |
export function copyToClipboard(string: string): boolean { | |
let textarea: HTMLTextAreaElement | |
let result: boolean | |
try { | |
navigator.clipboard.writeText(string) | |
} catch (e) { | |
try { | |
textarea = document.createElement('textarea') | |
textarea.setAttribute('position', 'fixed') | |
textarea.setAttribute('top', '0') | |
textarea.setAttribute('readonly', 'true') | |
textarea.setAttribute('contenteditable', 'true') | |
textarea.style.position = 'fixed' // prevent scroll from jumping to the bottom when focus is set. | |
textarea.value = string | |
document.body.appendChild(textarea) | |
textarea.focus() | |
textarea.select() | |
const range = document.createRange() | |
range.selectNodeContents(textarea) | |
const sel = window.getSelection() | |
sel.removeAllRanges() | |
sel.addRange(range) | |
textarea.setSelectionRange(0, textarea.value.length) | |
result = document.execCommand('copy') | |
} catch (err) { | |
result = null | |
} finally { | |
document.body.removeChild(textarea) | |
} | |
} | |
return !!result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment