Created
December 27, 2023 03:57
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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