Created
December 27, 2023 03:57
Revisions
-
che5ya created this gist
Dec 27, 2023 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,45 @@ 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!'); }