Skip to content

Instantly share code, notes, and snippets.

@Oluwa-nifemi
Created July 20, 2020 22:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oluwa-nifemi/2b9e6500c0c9ee6a7e6bdf51ead2f0f9 to your computer and use it in GitHub Desktop.
Save Oluwa-nifemi/2b9e6500c0c9ee6a7e6bdf51ead2f0f9 to your computer and use it in GitHub Desktop.
Copy to clipboard
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