Is there something better than document.execCommand?

Brent picture Brent · Sep 3, 2012 · Viewed 7.3k times · Source

When implementing a web-based rich-text editor, I read that document.execCommand is useful for performing operations on an HTML document (like making a selection bold). However, I need something a bit better. Specifically, I need to know exactly what text is added or removed from the innerHTML, and in what location (as an offset into the entire document's HTML representation).

I considered using the built in document.execCommand along side DOM4's mutation observer, but execCommand doesn't seem up to the task:

  • I don't see a way to "un-bold" a selection
  • the generated html seems to vary from browser to browser. (I'd like < span > tags not < b >, but consistency is more important)
  • and there's no information on what it does to handle redundantly nested/adjacent < span > tags.

Also, using mutation observer seems a bit overkill based on my needs.

My motivation: I'm trying to transmit document changes to the server periodically without re-transmitting the whole document. I'm sending the data as a collection of insertions and deletions upon the HTML representation. If someone knows a way to get this functionality out of, say, CKEditor (so I don't have to start from scratch), then I would love you forever.

Note: Performing a text diff is not an option, due to its poor performance on very large documents.

Otherwise, I'm not exactly afraid of trying to write something that does this. The methods provided by the DOM's range object would handle a lot of the heavy lifting. I'd also appreciate advice regarding this possibility.

Answer

naugtur picture naugtur · Sep 16, 2012

There is one alternative to using execCommand - implementing the whole interaction of an editor including blinking of a cursor. And it has been done. Google does it in docs, but there's something free and open-source too. Cloud9 IDE http://c9.io has an implementation. AFAIK, github uses that editor for some time now. And you surely can do anything under that, because there's no native code involved - like in execCommand

The repo is here: https://github.com/ajaxorg/cloud9 (it contains the whole IDE, you will need to find the code for the editor. )

Also - dom mutation events are deprecated. If you can drop support for old browsers, try mutation observer. If not - try to avoid detecting DOM changes at all and intercept changes in the editor's implementation. It might be the way to go for the new browsers too.