Created
August 25, 2022 04:46
-
-
Save nadyshalaby/99a538225cd552db8fbbc1d83ecabf75 to your computer and use it in GitHub Desktop.
Snippet that allows you to copy data to clipboard using javascript
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 fallbackCopyTextToClipboard(text) { | |
var textArea = document.createElement("textarea"); | |
textArea.value = text; | |
// Avoid scrolling to bottom | |
textArea.style.top = "0"; | |
textArea.style.left = "0"; | |
textArea.style.position = "fixed"; | |
document.body.appendChild(textArea); | |
textArea.focus(); | |
textArea.select(); | |
try { | |
var successful = document.execCommand('copy'); | |
var msg = successful ? 'successful' : 'unsuccessful'; | |
console.log('Fallback: Copying text command was ' + msg); | |
} catch (err) { | |
console.error('Fallback: Oops, unable to copy', err); | |
} | |
document.body.removeChild(textArea); | |
} | |
function copyTextToClipboard(text) { | |
if (!navigator.clipboard) { | |
fallbackCopyTextToClipboard(text); | |
return; | |
} | |
navigator.clipboard.writeText(text).then(function() { | |
console.log('Async: Copying to clipboard was successful!'); | |
}, function(err) { | |
console.error('Async: Could not copy text: ', err); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment