2

So I am using a MacBook and I have a copy button that copies a generated text input on a text field.

This is the code:

document.querySelector("#btnCopy").addEventListener('click', copy);
async function copy(){
    
    var text = document.querySelector("#docNumber");
    text.select();
    navigator.clipboard.writeText(text.value)
}

When I check the clipboard nothing has been copied.

Any suggestion of what is going on?

Thanks, community.

Danilo Ivanovic
  • 1,216
  • 1
  • 10
  • 18
Rafael Nicola
  • 74
  • 1
  • 11

2 Answers2

1

I think you need to assign the selected text to something.

let t = text.select();

or better yet:

navigator.clipboard.writeText(text.select())
polisen
  • 275
  • 1
  • 7
1

The following approach works in Chrome, Firefox, Internet Explorer and Edge, and in recent versions of Safari (copy support was added in version 10 which was released Oct 2016).

document.querySelector("#btnCopy").addEventListener('click', copyToClipboard);

function copyToClipboard() {
  let text = document.querySelector("#docNumber");
  text.select();
  text = text.value;

  if (window.clipboardData && window.clipboardData.setData) {
    // IE: prevent textarea being shown while dialog is visible
    return window.clipboardData.setData("Text", text);

  } else if (document.queryCommandSupported && 
             document.queryCommandSupported("copy")) {
    var textarea = document.createElement("textarea");
    textarea.textContent = text;
    // Prevent scrolling to bottom of page in MS Edge
    textarea.style.position = "fixed";
    document.body.appendChild(textarea);
    textarea.select();
    try {
      // Security exception may be thrown by some browsers
      return document.execCommand("copy");
    } catch (ex) {
      console.warn("Copy to clipboard failed.", ex);
      return false;
    } finally {
      document.body.removeChild(textarea);
    }
  }
}
<input id="docNumber" type="text" value="Clipboard text test">
<button id="btnCopy">Copy to Clipboard</button>

Reference:

ℛɑƒæĿᴿᴹᴿ
  • 4,983
  • 4
  • 38
  • 58