Created
July 20, 2020 22:02
-
-
Save Oluwa-nifemi/2b9e6500c0c9ee6a7e6bdf51ead2f0f9 to your computer and use it in GitHub Desktop.
Copy to clipboard
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) { | |
const 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 { | |
const successful = document.execCommand('copy'); | |
const 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); | |
} | |
export const 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