Is there a replacement for document.execCommand? (or is it safe to use document.execCommand?)

Both the change to MDN marking document.execCommand() as obsolete and a related change at https://github.com/mdn/browser-compat-data/commit/2d3890a were made in part to due to https://w3c.github.io/editing/ActiveDocuments/execCommand.html having a big red warning with the following statements:

This spec is incomplete and it is not expected that it will advance beyond draft status. Authors should not use most of these features directly, but instead use JavaScript editing libraries. The features described in this document are not implemented consistently or fully by user agents, and it is not expected that this will change in the foreseeable future.

As far as any replacement method in vanilla JavaScript, the same warning box says it’s:

predicted that in the future both specs will be replaced by Content Editable and Input Events

…but sadly, we’re not there yet. So the unfortunate current state of things is, even though we have no replacement yet, we know document.execCommand() as-is now doesn’t work cross-browser interoperably — and browser projects aren’t gonna be fixing it. That’s why the MDN warning says:

its use is discouraged… Try to avoid using it.

So, as a comment above says, it’s similar to the case of drag-and-drop: It’s known to be broken in a number of ways, and it’s been that way for a long time because fixing it is basically not practical.

And that’s why the red warning box in the spec also says that developers and authors:

should not use most of these features directly, but instead use JavaScript editing libraries

The available JavaScript editing libraries in online rich-text editor tools such as CKEditor and TinyMCE “paper over” all the underlying brokenness in document.execCommand() for you. If you were to try to write your own robust handling for document.execCommand() in vanilla JavaScript from scratch, you’d basically — after a lot of work and time — end up having repeated the work that was done to create the JavaScript libraries underlying those tools.

So the bottom line is: to save yourself a lot of time and work, use one of the available libraries.


It looks like the new standard will be Input Events Level 2.

The way I see it, it tries to fix the pain points of execCommand.