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>
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With