Javascript textarea undo redo

后端 未结 2 848
醉话见心
醉话见心 2020-12-01 06:41

I\'m making a small javascript editor (for a chrome extension) somewhat like the one on SO.

There\'s a toolbar for manipulation of the text in the textarea. (e.g. su

相关标签:
2条回答
  • 2020-12-01 07:18

    If the textarea has focus and its caret is at the correct position,

    document.execCommand("insertText", false, "the text to insert");
    

    will insert the text "the text to insert", preserving the browser's native undo stack. (See the work in progress HTML Editing API spec.) Chrome 18 supports this, but I'm unsure of the exact version it was introduced.

    0 讨论(0)
  • 2020-12-01 07:24

    You can probably simulate textInput events to manipulate the contents of the textarea. The changes made that way are respected by undo/redo, I think (I know they are in Safari)

    var element = document.getElementById('someTextarea');
    var text = 'This text will be inserted in the textarea';
    var event = document.createEvent('TextEvent');
    
    event.initTextEvent('textInput', true, true, null, text);
    element.dispatchEvent(event); // fire the event on the the textarea
    

    Basically, the text is inserted as though you pasted it yourself. So if something is selected, it'll be be replaced with the text. If there's no selection, the text will be inserted at the caret's position. And undo/redo should work normally (undoing/redoing the entire inserted string in one go), because the browser acts as if you typed/pasted it yourself.

    As I said, I know this works like a charm with undo/redo in Safari, so I'd assume it works in Chrome as well.

    0 讨论(0)
提交回复
热议问题