简体   繁体   中英

Event listener for undo in browsers

To give context, my team is building a rich text editor in the browser that needs to persist state to a server between sessions. The editor's state can obviously change from updates to the document that include keydown events, but we should also account for updates to the editor's stage that are triggered by undo/redo events .

Unfortunately the browser has no native undo/redo events ( ref ). One proposed hack floating around seems to be to stop propagation for keydown events that maps to undo's keyboard shortcut in addition to disabling the context menu. However , this still leaves open the ability for the user to navigate directly to Edit -> Undo in the application's menu bar , which will directly trigger a document.execCommand('undo') and doesn't fire an event. As a result we wouldn't know to send an update to the server.

Here's a W3C thread on this issue. As of the writing of this, it appears that a solution is still in the works...

When Quill , another browser text editor, ran into this issue their team seemed to advise : "disable the native undo/stack", which is what Facebook's Draft.js actually does . Given that seems to be what we're working with, does anyone know of a way to disable/substitute the browser's native undo/redo stack ? Obviously, this is an aggressive solution, but, as of the writing of this, that seems to be the only option.

In the meantime, the answer to this question probably buried somewhere in the Draft's code. If no one beats my team to it, I'll report back on what Draft seems to be doing. Thought it was at least worth documenting this issue.

Likely the best solution is to listen for a debounced onChange event from the contentEditable element. This doesn't allow for custom behavior regarding undo, but it should solve the main issue. Also adding a beforeunload event to alert the user to potential unsaved changes should handle additional edge cases.

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