Contenteditable allowing only plain text
<p>I'm trying to make a contenteditable that only accepts plain text.</p>
<p>What I want is to listen to paste event and then remove all html and paste it on the contenteditable only as plain text.</p>
<p>In order to do that I've already tried two different approachs, based answers to similar questions, but those two approachs have problems.</p>
<p><strong>First:</strong>
This one isn't using &quot;paste&quot; listener, is instead listening for input (not ideal for this case), this was a solution to avoid using <a href="https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent" rel="noreferrer">Clipboard API</a>.</p>
<p><em><strong>Problem:</strong></em> This works fine on chrome but not on firefox and IE, when you copy and paste the html it sucessfully removes html and only paste text, but when continuing to write text, the caret is always taken to the beginning of the contenteditable.</p>
<pre class="lang-js prettyprint-override"><code>function convertToPlaintext() {
  var textContent = this.textContent;
  this.textContent = textContent;
}

var contentEditableNodes = document.querySelectorAll('.plaintext[contenteditable]');

[].forEach.call(contentEditableNodes, function(div) {
  div.addEventListener(&quot;input&quot;, convertToPlaintext, false);
});
</code></pre>
<p><em>You can try it here/code on which I based:</em> <a href="http://jsbin.com/moruseqeha/edit?html,css,js,output" rel="noreferrer">http://jsbin.com/moruseqeha/edit?html,css,js,output</a></p>
<p><strong>Second:</strong>
Since the first one failed and isn't listening to &quot;paste&quot; event only, I've then decided to give it a try using <a href="https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent" rel="noreferrer">Clipboard API</a>.
The problem here is that on IE <em>document.execCommand(&quot;insertHTML&quot;, false, text);</em> doesn't seem to work.
This works on chrome, firefox (tested on v41 and v42) and edge.</p>
<pre class="lang-js prettyprint-override"><code>document.querySelector(&quot;.plaintext[contenteditable]&quot;).addEventListener(&quot;paste&quot;, function(e) {
  e.preventDefault();
  var text = &quot;&quot;;
  if (e.clipboardData &amp;&amp; e.clipboardData.getData) {
    text = e.clipboardData.getData(&quot;text/plain&quot;);
  } else if (window.clipboardData &amp;&amp; window.clipboardData.getData) {
    text = window.clipboardData.getData(&quot;Text&quot;);
  }
  document.execCommand(&quot;insertHTML&quot;, false, text);
});
</code></pre>
<p>You can try it here: <a href="http://jsfiddle.net/marinagon/461uye5p/" rel="noreferrer">http://jsfiddle.net/marinagon/461uye5p/</a></p>
<p>Can anyone help me find a solution for some of this problems or anyone has a better solution than the ones presented here?</p>
<p><em><strong>I'm aware that I could use textarea, but I have reasons not to use it.</strong></em></p>