简体   繁体   中英

Is there something better than document.execCommand?

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.

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.

Trix富文本编辑器,从他们的描述来看,避免不一致的 execCommand 是项目的重点。

It seems the new standard will be Input Events Level 2 . To me it looks like it will be a revised improved version of execCommand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM