Skip to content

Instantly share code, notes, and snippets.

@che5ya
Created December 27, 2023 03:57
Show Gist options
  • Save che5ya/9bc977a881d6b5944d06997bd0c27313 to your computer and use it in GitHub Desktop.
Save che5ya/9bc977a881d6b5944d06997bd0c27313 to your computer and use it in GitHub Desktop.
Example of a function using JavaScript to copy the provided text to the clipboard
const onClickCopyText = text => {
// Step 1: Using Clipboard API
if (window?.navigator?.clipboard && window?.navigator?.clipboard?.writeText) {
return window.navigator.clipboard.writeText(text);
} else {
return fallbackCopyTextToClipboard(text);
}
};
const fallbackCopyTextToClipboard = text => {
// Step 2: Alternative Copying Text without Clipboard API
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.setAttribute('readonly', '');
textarea.style.position = 'absolute';
textarea.style.left = '-9999px';
document.body.appendChild(textarea);
textarea.select();
try {
const successful = document.execCommand('copy');
const msg = successful ? 'successful' : 'unsuccessful';
console.log(`Fallback: Copying text command was ${msg}`);
return successful;
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
return false;
} finally {
document.body.removeChild(textarea);
}
};
// Test Way 1
onClickCopyText('This text will be copied to clipboard.')
.then(() => console.log('async: Success!'))
.catch(err => console.error('async: Failed!.', err));
// Test Way 2
const copied = onClickCopyText('This text will be copied to clipboard.');
if (copied) {
console.log('Sync: Success!');
} else {
console.error('Sync: Failed!');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment