Search code examples
javascripthtmldomcontenteditable

Listen to undo/redo event in contenteditable div


Is there a way to listen on all the ways a user could trigger an undo on a contenteditable div? For example when the user hits Control+Z, Right-click -> Undo, or in the file menu Edit -> Undo.

I'm not looking for undo/redo algorithms or implementations, just the ability to listen to the event and overwrite the behavior.


Solution

  • You can get event.inputType of input event. Check for "historyUndo" / "historyRedo":

    var div = document.getElementById("mydiv");
    div.addEventListener("input", function(e) {
      switch(e.inputType){
        case "historyUndo": alert("You did undo"); break;
        case "historyRedo": alert("You did redo"); break;
      }
    });
    <div id="mydiv" contenteditable="true">Hello world!</div>

    In recent browsers, you can cancel the event using the beforeinput event (not in Firefox yet):

    var div = document.getElementById("mydiv");
    div.addEventListener("beforeinput", function(e) {
      switch(e.inputType){
        case "historyUndo": e.preventDefault(); alert("Undo has been canceled"); break;
        case "historyRedo": e.preventDefault(); alert("Redo has been canceled"); break;
      }
    });
    <div id="mydiv" contenteditable="true">Hello world!</div>

    References: