Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
Simple navigator.clipboard.writeText() does not work

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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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:

  • How do I copy to the clipboard in JavaScript?
about 4 years ago · Juan Pablo Isaza Relatório

0

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

let t = text.select();

or better yet:

navigator.clipboard.writeText(text.select())
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda