Javascript trick for 'paste as plain text` in execCommand Javascript trick for 'paste as plain text` in execCommand javascript javascript

Javascript trick for 'paste as plain text` in execCommand


It will intercept the paste event, cancel the paste, and manually insert the text representation of the clipboard:
http://jsfiddle.net/HBEzc/. This should be the most reliable:

  • It catches all kinds of pasting (Ctrl+V, context menu, etc.)
  • It allows you to get the clipboard data directly as text, so you don't have to do ugly hacks to replace HTML.

I'm not sure of cross-browser support, though.

editor.addEventListener("paste", function(e) {    // cancel paste    e.preventDefault();    // get text representation of clipboard    var text = (e.originalEvent || e).clipboardData.getData('text/plain');    // insert text manually    document.execCommand("insertHTML", false, text);});


I couldn't get the accepted answer here to work in IE so I did some scouting around and came to this answer which works in IE11 and the latest versions of Chrome and Firefox.

$('[contenteditable]').on('paste', function(e) {    e.preventDefault();    var text = '';    if (e.clipboardData || e.originalEvent.clipboardData) {      text = (e.originalEvent || e).clipboardData.getData('text/plain');    } else if (window.clipboardData) {      text = window.clipboardData.getData('Text');    }    if (document.queryCommandSupported('insertText')) {      document.execCommand('insertText', false, text);    } else {      document.execCommand('paste', false, text);    }});


A close solution as pimvdb. But it's working of FF, Chrome and IE 9:

editor.addEventListener("paste", function(e) {    e.preventDefault();    if (e.clipboardData) {        content = (e.originalEvent || e).clipboardData.getData('text/plain');        document.execCommand('insertText', false, content);    }    else if (window.clipboardData) {        content = window.clipboardData.getData('Text');        document.selection.createRange().pasteHTML(content);    }   });