To paste as plain text with JavaScript execCommand, we get the pasted data as plain text before we insert it.
For instance, we write
editor.addEventListener("paste", (e) => {
e.preventDefault();
const text = e.clipboardData.getData("text/plain");
document.execCommand("insertHTML", false, text);
});
to listen to the past event on editor
with addEventListener
.
In it, we call preventDefault
to stop the default paste behavior.
Then we get the pasted text as plain text by calling clipboardData.getData
with 'text/plain'
,
Finally, we call execCommand
to insert the text
into editor
.