execCommand() is now obsolete, what's the alternative?

css, execcommand, html, javascript

Solution

Year 2022–2024 answer: The `execCommand()` is officially obsolete/deprecated but there's no alternative. So if you must have rich text support, you have to keep using `execCommand()` and figure out yourself what actually works with browsers that you want to support.

Note that real world user agents (browsers such as Chrome, Firefox and Safari) cannot drop support for `execCommand()` because so many services require support for it. The sad state of things is that HTML5 cannot specify any common ground. This is because browser vendors do not agree how `execCommand()` should work. So nothing can be specified for HTML5, which has the overall objective to specify all stuff – and only stuff – that's needed for full interoperability for any new browser to enter market. However, in my opinion HTML5 fails here because `execCommand()` compatibility is actually required for any new browser to enter market. So it would make sense to standardize at least one of the browser specific implementations as the official one.

All the current standardization efforts (Input Events 2, Clipboard API) fail to even try to cover the features that `execCommand()` actually does (for example, undo/redo, actually changing content within the selection range).

The hardest part to solve is the caret movement, selecting text, different IME (Input Method Editor) behavior and handling native clipboard. These all interact with each other in various ways depending on browser and operating system. For example, the behavior that iOS Safari has on iPad while writing Traditional Chinese is totally different from Firefox on Windows with Thai IME. Which is again totally different from Chrome running on Chromebook while writing Finnish or entering emoji characters with multiple UNICODE point encoding. And as none of the available JS APIs disclose all the details, you MUST use `contenteditable` and possibly `execCommand()`, too, for most browsers to get correct input from the IME.

Also note that e.g. Android GBoard needs to also know about the surrounding text within the same editable content because it uses AI logic to correctly figure out which word suggestions to give to the user while inputting text, so you cannot fake this with a single empty invisible textarea under the caret because that would be missing the required context. That hasn't prevented people from trying to do exactly that but it fails in practice in various ways.

This situation has already been going for over five years so don't expect any rapid changes either.

Problem

I intended to use `Document.execCommand()` method along with `contenteditable` attribute to build my custom WYSIWYG editor. But when I checked the documentation for `Document.execCommand()`, I found that it's now obsolete. What's the modern (or extant) alternative for it?

Original source

Related problems