I want to make div with contentEditable attribute which is allowing only text. It's easily achievable in Chrome by using:
<div contenteditable="plaintext-only"></div>
However it doesn't work in Firefox. Is there a way how to make text-only contenteditable div in Firefox ? I know it is possible, because Google Plus has such div, but I don't know how they do it.
You can
paste
event listener to an elementthis will prevent image pasting or pasting text with format
yourEditableElement.addEventListener('paste', (event) => {
event.preventDefault();
const text = event.clipboardData?.getData('text/plain');
const selectedRange = window.getSelection()?.getRangeAt(0);
if (!selectedRange || !text) {
return;
}
selectedRange.deleteContents();
selectedRange.insertNode(document.createTextNode(text));
selectedRange.setStart(selectedRange.endContainer, selectedRange.endOffset);
});
Here is an example https://codesandbox.io/p/sandbox/contenteditable-plain-text-only-vv8dk?file=%2Fsrc%2FEditable.tsx