javascriptexeccommandobsolete

Beginner - Why is execCommand() obsolete?


Not a coding question, and the question applies to a wider tag of XYZ becoming obsolete, but asking as there seems to be tons of comments on the web about how there are so many apps out there that use this command.

Why is this now obsolete? (tried executing on vscode, would not work)


Solution

  • Based on the MDN entry for Document.execCommand, in most cases the APIs made available by execCommand can be achieved using other modern, purpose-built JavaScript APIs that behave the same way across browsers.

    Each command in execCommand's toolbox was contentiously implemented in different ways across browsers meaning that testing on every single browser was a necessity of web development. Just skimming through the draft spec you linked in the comments shows all of the notes detailing some of the different ways they were implemented. Because of these differences there was a shift away from HTML-based rich-text document rendering to canvas-based rendering for Google Docs and img-based rendering for Office 365 Web Apps (at least for viewing them, editing is still HTML-based).

    Additionally, the MDN entry notes:

    Return value

    A boolean value that is false if the command is unsupported or disabled.

    Note: document.execCommand() only returns true if it is invoked as part of a user interaction. You can't use it to verify browser support before calling a command. From Firefox 82, nested document.execCommand() calls will always return false.

    Because execCommand can only be invoked as part of user interaction, it might work in one bit of your code, and not in another - which can cause time-consuming headaches that involve learning the intricacies of JavaScript's event loop.

    Importantly, with the advent of JavaScript running on mobile devices and modern JavaScript frameworks having their own "event->queue->render" loops, what even defines a user interaction event? A click, tap, keypress, etc? What about a screen rotation or resizing the window? What about asynchronous event changes where you make a server request and then show the user something based on the result? How would the engine know those two things are linked together with modern Promise-based APIs rather than callback-based APIs?

    If you want to do some further digging, take a look at this thread on another question asking about what replacements are available to execCommand().