Modify copied content on copy event

Viewed 29

I'm trying to modify the content a user copies and remove hidden chars from the text and html.

My current solution:

this.bodyTextRef.current.addEventListener("copy", this.onCopyBodyText);

onCopyBodyText(event) {
  const selection = document.getSelection();

  const fragment = selection.getRangeAt(0).cloneContents();
  const html = $('<div>').append(fragment).html();
  event.clipboardData.setData("text/html", html.replace(/\uFEFF/g, ""));

  let trimmedSelection = selection?.toString()?.trim();
  trimmedSelection = trimmedSelection?.replace(/\uFEFF/g, "");
  event.clipboardData.setData("text/plain", trimmedSelection);

  event.preventDefault();
}

the text/plain works as expected, but the text/html can lose its original structure. for example if I copy -

  1. a
  2. a
  3. a

the pasted result will be -

  • a
  • a
  • a

because the parent tag <ol> is not found in the range.

when not trying to modify the copied content the html is copied properly (but with the hidden chars).

Is it possible to get the original copied html and modify it directly?

0 Answers
Related