Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
Simple navigator.clipboard.writeText() no funciona

Así que estoy usando una MacBook y tengo un botón de copia que copia una entrada de texto generada en un campo de texto.

Este es el código:

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

Cuando reviso el portapapeles no se ha copiado nada.

¿Alguna sugerencia de lo que está pasando?

Gracias, comunidad.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

El siguiente enfoque funciona en Chrome, Firefox, Internet Explorer y Edge, y en versiones recientes de Safari (la compatibilidad con copias se agregó en la versión 10, que se lanzó en octubre de 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>

Referencia:

  • ¿Cómo copio al portapapeles en JavaScript?
about 4 years ago · Juan Pablo Isaza Report

0

Creo que necesitas asignar el texto seleccionado a algo.

 let t = text.select();

o mejor aún:

 navigator.clipboard.writeText(text.select())
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!