Skip to content

Instantly share code, notes, and snippets.

@che5ya
Created December 27, 2023 03:57

Revisions

  1. che5ya created this gist Dec 27, 2023.
    45 changes: 45 additions & 0 deletions copyText.func.js
    Original 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!');
    }