Created
August 5, 2021 07:38
-
-
Save ravishakya/4d5b02a55364c3d4d0bd6dc1ac6abb0f to your computer and use it in GitHub Desktop.
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
function copyToClipboard(textToCopy) { | |
// navigator clipboard api needs a secure context (https) | |
if (navigator.clipboard && window.isSecureContext) { | |
// navigator clipboard api method' | |
return navigator.clipboard.writeText(textToCopy); | |
} else { | |
// text area method | |
let textArea = document.createElement("textarea"); | |
textArea.value = textToCopy; | |
// make the textarea out of viewport | |
textArea.style.position = "fixed"; | |
textArea.style.left = "-999999px"; | |
textArea.style.top = "-999999px"; | |
document.body.appendChild(textArea); | |
textArea.focus(); | |
textArea.select(); | |
return new Promise((res, rej) => { | |
// here the magic happens | |
document.execCommand('copy') ? res() : rej(); | |
textArea.remove(); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment