Tengo un texto que he ingresado en "dangerouslySetInnerHTML" para mostrar el formato apropiado. El formato incluye saltos de línea, etiquetas en negrita e hipervínculos.
Quiero que un usuario pueda copiar desde el portapapeles conservando el formato de la plantilla.
Logré copiar desde el portapapeles, pero el texto copiado incluye el html sin procesar y no el formato.
Ex.
const myTemplate = <p>Hello <a href="${link}">User</a></p> //Template <Dialog isShown={showDialog} onCloseComplete={() => setShowDialog(false)} topOffset={4} footer={ <Button onClick={() => navigator.clipboard.writeText( document?.getElementById('to-copy')?.innerHTML, ) } > Click here to copy the template </Button> <div id="to-copy" dangerouslySetInnerHTML={{ __html: `${myTemplate}` }}></div>Salida deseada:
Hola usuario (hipervínculo)
No estoy seguro si entiendo los matices de su pregunta, pero aquí hay algunas cosas que podrían (espero) ayudar.
function copyToClip(str) { function listener(e) { e.clipboardData.setData("text/html", str); e.clipboardData.setData("text/plain", str); e.preventDefault(); } document.addEventListener("copy", listener); document.execCommand("copy"); document.removeEventListener("copy", listener); }; <button onclick="copyToClip(document.getElementById('richtext').innerHTML)"> Copy to Clipboard </button> <div> <br> Click the above <kbd>Copy to Clipboard</kbd> button and then paste the clipboard contents into MS Word or LibreOffice Writer. <br><br> Beneath this div is an invisible (display:none) div that contains formatted text (bolded, italicized, colored, different font). <i>The contents of that invisible div are copied to your clipboard when you click the Copy To Clipboard button up top.</i> </div> <div id=richtext style="display:none"> The data in this div is not visible. It contains rich text. Rich (ie "formatted") data can also be generated by javascript. The next word is <b>bolded</b>, and the next one is in <i>italics</i>. <span style="font:24px Arial; color:purple;">Some large purple text</span>. You can use two setData directives to insert TWO copies of this text into the same clipboard, one that is plain and one that is rich. That way your users can paste into either a <ul> <li>plain text editor</li> <li>or into a rich text editor</li> </ul> Here is a <a href="https://rumble.com">Link to Rumble</a> - you must Ctrl-Click the link in Word. </div>Documentación para la API del Portapapeles (MDN)
Anteriormente, usamos document.execCommand() para escribir en el portapapeles. Ahora está en desuso (y puede requerir poner la página en designMode ), pero dependiendo de sus requisitos, podría ser útil.
¿Cómo estás copiando a tu portapapeles?
Es posible que deba convertirlo en una cadena sin procesar y usar una biblioteca de utilidades como la copia del portapapeles ( https://www.npmjs.com/package/clipboard-copy )