Skip to content

Instantly share code, notes, and snippets.

@mathesond2
Created May 10, 2022 21:03
Show Gist options
  • Save mathesond2/ad01434e9d25d325d3d6501a9e9893ce to your computer and use it in GitHub Desktop.
Save mathesond2/ad01434e9d25d325d3d6501a9e9893ce to your computer and use it in GitHub Desktop.
copy to clipboard
export const copyToClipBoard = async (copyText: string): Promise<boolean> => {
if (navigator.clipboard) {
try {
await navigator.clipboard.writeText(copyText);
return true;
} catch (err) {
throw err;
}
}
// Legacy fallback
else {
try {
const textArea = document.createElement('textarea');
textArea.value = copyText;
// Avoid scrolling to bottom
textArea.style.top = '0';
textArea.style.left = '0';
textArea.style.position = 'fixed';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
const copy = await document.execCommand('copy');
document.body.removeChild(textArea);
return copy;
} catch (err) {
throw err;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment