Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda