Copy and Paste rich text to mailto body in react from clipboard

Viewed 533

I have a table in which I want the user to be able to send this table via email by copying and paste to mailto subject on click.

Here is a live demo on code sandbox: copy and paste rich text

A function to copy and paste rich text to mailto body from clipboard

  const copyToClip = () => {
    let range = document.createRange();
    range.selectNodeContents(tableRef.current);
    let sel = window.getSelection();
    sel.removeAllRanges();
    sel.addRange(range);
    document.execCommand("Copy");
    sel.removeAllRanges();
    //paste the copied data to mailto body
    document.addEventListener("paste", function (event) {
      var clipText = event.clipboardData.getData("Text");
      window.location = `mailto:?subject=I wanted you to see this site&body=${clipText}`;
    });
  };

The expected result when the user clicks the copy button, it opens the client default email and past the table to the body like this below.

enter image description here

Note: I am able to send the copied data as a string but not a rich-text.

What do I need to to do solve the problem?

1 Answers

Change:

var clipText = event.clipboardData.getData("Text");

to

var clipText = encodeURIComponent(event.clipboardData.getData("Text"));
Related