Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop pasting html style in a contenteditable div only paste the plain text

Tags:

javascript

css

I am using a contenteditable div, when I tried to paste something with style, it was suppose to only copy the plain text, but it got the style as well, does anyone know how to force it to convert to plain text when I paste it or anyone has a better solution

Here is my code:

    <div contenteditable="true">   
      This text can be edited by the user. 
    </div>

enter image description here enter image description here

like image 691
FlyingBurger Avatar asked Nov 21 '19 17:11

FlyingBurger


2 Answers

When you paste in rich content, it will be displayed as rich content. So you would need to capture the paste event, prevent the default action, and read the text from the clipboard.

var ce = document.querySelector('[contenteditable]')
ce.addEventListener('paste', function (e) {
  e.preventDefault()
  var text = e.clipboardData.getData('text/plain')
  document.execCommand('insertText', false, text)
})
  [contenteditable] {
    background-color: black;
    color: white;
    width: 400px;
    height: 200px;
  }
<div contenteditable="true"></div>

<div>
  <h1>Test content</h1>
  <p style="color:red">Copy <em>this</em> <u>underlined</u></p>
</div>
like image 200
epascarello Avatar answered Oct 11 '22 06:10

epascarello


You can intercept the "paste" event and replace the content of the target.

/* Derrived from: https://stackoverflow.com/a/6035265/1762224 */
const onPastePlainText = (e) => {
  var pastedText = undefined;
  if (window.clipboardData && window.clipboardData.getData) { // IE
    pastedText = window.clipboardData.getData('Text');
  } else if (e.clipboardData && e.clipboardData.getData) {
    pastedText = e.clipboardData.getData('text/plain');
  }
  e.target.textContent = pastedText;
  e.preventDefault();
  return false;
}

document.querySelector('.ediatable-div').addEventListener('paste', onPastePlainText);
.ediatable-div {
  border: 2px inset #EEE;
  height: 25vh;
}

/* Placeholder - Derrived from: https://stackoverflow.com/a/20300212/1762224 */
[contentEditable=true]:empty:not(:focus):before {
  content: attr(data-text);
  color: #AAA;
}
<div class="ediatable-div" contenteditable="true" data-text="Paste copied HTML here"></div>
<div>
  <p style="text-decoration:underline">Copy <strong>me</strong>, I have <em>style</em>!</p>
</div>
like image 29
Mr. Polywhirl Avatar answered Oct 11 '22 07:10

Mr. Polywhirl