Skip to content

Instantly share code, notes, and snippets.

@alaminfirdows
Created May 15, 2023 05:38
Show Gist options
  • Save alaminfirdows/9966ebd6876c0d605c54637ffcd14034 to your computer and use it in GitHub Desktop.
Save alaminfirdows/9966ebd6876c0d605c54637ffcd14034 to your computer and use it in GitHub Desktop.
copy to clipboard
export const copyToClipboard = async (textToCopy) => {
// Navigator clipboard api needs a secure context (https)
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(textToCopy);
} else {
// Use the 'out of viewport hidden text area' trick
const textArea = document.createElement('textarea');
textArea.value = textToCopy;
// Move textarea out of the viewport so it's not visible
textArea.style.position = 'absolute';
textArea.style.left = '-999999px';
document.body.prepend(textArea);
textArea.select();
try {
document.execCommand('copy');
} catch (error) {
console.error(error);
} finally {
textArea.remove();
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment