I have some text that I have inputted into a "dangerouslySetInnerHTML" to display appropriate formatting. The formatting includes line breaks, bold tags and hyperlinks.
I want a user to be able to copy from clipboard while preserving the formatting of the template.
I managed to copy from clipboard but the copied text includes the raw html and not the formatting.
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>
Desired Output:
Hello User(hyperlink)
CodePudding user response:
How are copying to your clipboard?
You might have to convert it to a raw string and use utility library such as clipboard-copy (https://www.npmjs.com/package/clipboard-copy)
CodePudding user response:
Unsure if I understand the nuances of your question, but here are some things that might (I hope) help.
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 (i.e. "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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
References:
Documentation for the Clipboard API (MDN)
Previously, we used document.execCommand()
to write to the clipboard. It is now deprecated (and may require putting the page into designMode
), but depending on your requirements it might be useful.