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

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>

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>

Tags:

Javascript

Css