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

151
Vistas
No se puede recopilar HTML copiado durante el evento de copia

Necesita recopilar HTML (para eliminar parte del estilo) durante el evento de copia.

Actualmente, intentando hacer lo siguiente:

Agregue un oyente para el evento 'copiar'

 document.addEventListener('copy', (e) => { console.log("e.target:" + e.target); });

Y luego use la API del portapapeles para copiar el elemento en la línea de:

 var blob = new Blob([html], {type: "text/html"}); var item = new ClipboardItem({"text/html": blob}); navigator.clipboard.write([item])

Sin embargo, cuando intento recopilar html en el evento de copia, estoy usando e.target para recopilar el HTML. Parece que e.target.nextElementSibling cuando se llama recursivamente debería dar el valor del siguiente elemento. Sin embargo, cuando se seleccionan elementos de una lista (sin que se seleccione toda la lista), parece que no funciona como se esperaba.

Como ejemplo:

 <html> <head> <title> The simplest HTML example </title> </head> <body> <h1> This is an HTML Page </h1> <ul> <li> <a href="https://www.google.com/">goog</a> </li> <li> <a href="https://www.bing.com/">bing</a> </li> </ul> Not in list: <a href="https://www.google.com/">goog</a> <a href="https://www.bing.com/">bing</a> </body> </html>
 document.addEventListener('copy', (e) => { console.log("e.target:" + e.target); console.log("e.target:" + e.target.nextElementSibling); });

JSFiddle: https://jsfiddle.net/q8d9vogu/9/

Seleccionando Not in list: goog bing muestra ambos elementos. Al seleccionar la lista goog & bing SOLAMENTE muestra google uno (e.target.nextElementSibling es nulo).

¿Cómo debemos recopilar el HTML que se copia dentro del evento de copia? (contexto: esto se está ejecutando dentro de la extensión VSCode)

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Respondiendo a mi propia pregunta con una posible solución en caso de que otros se encuentren con esto. Lo siguiente parece estar haciendo el truco de agarrar HTML y copiarlo en el portapapeles:

 document.addEventListener('copy', (e) => { const htmlSelection = getHTMLOfSelection(); if (htmlSelection !== undefined){ copyToClipboard(htmlSelection); } }); /** * Based off of: https://stackoverflow.com/a/5084044/7858768 * */ function getHTMLOfSelection () { let range; if (document.selection && document.selection.createRange) { range = document.selection.createRange(); return range.htmlText; } else if (window.getSelection) { const selection = window.getSelection(); if (selection.rangeCount > 0) { range = selection.getRangeAt(0); const clonedSelection = range.cloneContents(); const div = document.createElement('div'); div.appendChild(clonedSelection); return div.innerHTML; } else { return undefined; } } else { return undefined; } } /** Based off of: * https://stackoverflow.com/a/64711198/7858768 * https://stackoverflow.com/a/57279336/7858768 */ function copyToClipboard(html) { const container = document.createElement('div'); container.innerHTML = html; container.style.position = 'fixed'; container.style.pointerEvents = 'none'; container.style.opacity = 0; const blob = new Blob([html], {type: "text/html"}); const item = new ClipboardItem({"text/html": blob}); navigator.clipboard.write([item]).then(function() { console.log("Copied to clipboard successfully!"); }, function(error) { console.error("Unable to write to clipboard. Error:"); console.log(error); }); } ```
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