0

I am trying to copy text as an onClick event, but it doesn't seem to pick up the value. Here's what I have:

  const copyText = () => {
    const input = document.createElement("input");
    input.innerHTML = 'test text';
    document.body.appendChild(input);
    input.select();
    document.execCommand("copy");
    document.body.removeChild(input);
    console.log("input", input);
  };

  copyText();

What am I doing wrong?

Mike K
  • 7,621
  • 14
  • 60
  • 120
  • did my answer solve your problem? If not, you can find plenty of inspiration [here](https://stackoverflow.com/q/400212/12917821). – Kaspar Etter Feb 27 '20 at 11:39

1 Answers1

1

To answer your question "What am I doing wrong?", you should probably use input.value instead of input.innerHTML. However, getting "copy to clipboard" to work on all platforms is a nightmare. After quite a bit of research and experimentation, I ended up with:

// Adapted from https://gist.githubusercontent.com/Chalarangelo/4ff1e8c0ec03d9294628efbae49216db/raw/cbd2d8877d4c5f2678ae1e6bb7cb903205e5eacc/copyToClipboard.js.
export function copyToClipboard(text: string): boolean {
    // Create and append textarea to body:
    const textarea = document.createElement('textarea');
    textarea.setAttribute('readonly', 'true'); // Method needed because of missing TypeScript definition.
    textarea.contentEditable = 'true';
    textarea.style.position = 'absolute';
    textarea.style.top = '-1000px';
    textarea.value = text;
    document.body.appendChild(textarea);

    // Save the current selection of the user:
    const selectedRange = document.getSelection()!.rangeCount > 0 ? document.getSelection()!.getRangeAt(0) : false;

    // Select the content of the textarea:
    textarea.select(); // Ordinary browsers
    textarea.setSelectionRange(0, textarea.value.length); // iOS

    // Try to copy the range to the clipboard:
    let success: boolean;
    try {
        success = document.execCommand('copy');
    } catch (error) {
        console.error('Could not copy to the clipboard.', error);
        alert('Could not copy to the clipboard.');
        success = false;
    }

    // Remove the added textarea again:
    document.body.removeChild(textarea);

    // Restore the selection of the user:
    if (selectedRange) {
        document.getSelection()!.removeAllRanges();
        document.getSelection()!.addRange(selectedRange);
    }

    return success;
}

Please note that this is written in TypeScript. For JavaScript, just remove all : string, : boolean and !.

Kaspar Etter
  • 3,155
  • 1
  • 14
  • 21