Skip to content

Instantly share code, notes, and snippets.

@hctilg
Created October 8, 2024 20:23
Show Gist options
  • Save hctilg/668846544ad9569f4ca5216febbd0a68 to your computer and use it in GitHub Desktop.
Save hctilg/668846544ad9569f4ca5216febbd0a68 to your computer and use it in GitHub Desktop.
Copy to clipboard with Javascript
function copyToClipboard(text, success) {
if (navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(text).then(success).catch(err => {
console.error('Failed to copy text: ', err);
});
} else {
const textarea = document.createElement('textarea');
textarea.value = text;
document.body.appendChild(textarea);
textarea.select();
textarea.setSelectionRange(0, text.length);
document.execCommand('copy');
document.body.removeChild(textarea);
success();
}
}
copyToClipboard("Hello, world!", () => {
alert('Copied to clipboard');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment