Javascript trick for 'paste as plain text` in execCommand

Googlebot picture Googlebot · Aug 19, 2012 · Viewed 94.9k times · Source

I have a basic editor based on execCommand following the sample introduced here. There are three ways to paste text within the execCommand area:

  • Ctrl+V
  • Right Click -> Paste
  • Right Click -> Paste As Plain Text

I want to allow pasting only plain text without any HTML markup. How can I force the first two actions to paste Plain Text?

Possible Solution: The way I can think of is to set listener for keyup events for (Ctrl+V) and strip HTML tags before paste.

  1. Is it the best solution?
  2. Is it bulletproof to avoid any HTML markup in paste?
  3. How to add listener to Right Click -> Paste?

Answer

pimvdb picture pimvdb · Aug 19, 2012

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);
});