Modify copied content on copy event

Issue

This Content is from Stack Overflow. Question asked by Omer Nave

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

My current solution:

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

    const fragment = selection.getRangeAt(0).cloneContents();
    const html = $('<div>').append(fragment).html();

    let trimmedSelection = selection?.toString()?.trim();
    trimmedSelection = trimmedSelection?.replace(/uFEFF/g, "");
    event.clipboardData.setData("text/plain", trimmedSelection);
    event.clipboardData.setData("text/html", html.replace(/uFEFF/g, ""));
    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

is it possible to get the copied html and modify it directly?



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?