We can paste plain text into a content editable element by listening to the paste event and modifying the pasting behavior.
For instance, if we have the following div:
<div contenteditable>
</div>
Then we can modify the paste behavior by listening to the paste event:
const editor = document.querySelector('div')
editor.addEventListener("paste", (e) => {
e.preventDefault();
const text = e.clipboardData.getData('text/plain');
document.execCommand("insertHTML", false, text);
});
We get the div with document.querySelector .
Then we listen to the paste event with addEventListener .
We pass in a callback that calls e.preventDefault to stop the default paste behavior.
Then we get the pasted text with the e.clipboard.getData method.
We pass in 'text/plain' to get the pasted data as plain text.
And then we call document.execCommand to run the insertHTML command with the text to paste it into the editor div as plain text.