Created
December 30, 2023 08:18
-
-
Save alaminfirdows/7189a03dd0657cd9fd4b61d485e0dc0f to your computer and use it in GitHub Desktop.
This JavaScript function, copyToClipboard, facilitates easy text copying to the clipboard. It first checks for compatibility with the modern Clipboard API in secure contexts. If supported, it uses the API for asynchronous clipboard writes. In cases where the API is unavailable or the context is not secure, it employs the 'out of viewport hidden …
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
export const copyToClipboard = async (textToCopy: string) => { | |
// Navigator clipboard api needs a secure context (https) | |
if (navigator.clipboard && window.isSecureContext) { | |
await navigator.clipboard.writeText(textToCopy); | |
} else { | |
// Use the 'out of viewport hidden text area' trick | |
const textArea = document.createElement('textarea'); | |
textArea.value = textToCopy; | |
// Move textarea out of the viewport so it's not visible | |
textArea.style.position = 'absolute'; | |
textArea.style.left = '-999999px'; | |
document.body.prepend(textArea); | |
textArea.select(); | |
try { | |
document.execCommand('copy'); | |
} catch (error) { | |
console.error(error); | |
} finally { | |
textArea.remove(); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment