htmlcontenteditable

How to make HTML5 contenteditable div allowing only text in firefox?


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.


Solution

  • You can

    1. attach an paste event listener to an element
    2. prevent default event (pasting anything)
    3. try to find plain text in clipboard
    4. if any text found -> emulate pasting only plain text

    this 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