Is it possible to edit a text input with javascript and add to the Undo stack?
Here's a solution which works in Firefox too, is the most performant one and offers undo functionality everywhere except Firefox (where it just isn't possible natively)
// Solution
function insertText(textarea, text) {
// https://stackoverflow.com/a/55174561/288906
if (!document.execCommand('insertText', false, text)) {
textarea.setRangeText(text);
}
}
// Demo code to add text on click
const textarea = document.querySelector('textarea');
textarea.onclick = () => insertText(
textarea,
'@'
);
<textarea>Click in here to add text</textarea>
I also packaged this up as an npm module, improving consistency across browsers.
I found a solution that works at https://stackoverflow.com/a/10345596/1021426
By replacing the "field.value = ..." lines with:
document.execCommand("insertText", false, processedText);
...and moving "field.focus()" to before that line, I was able to achieve the undo/redo functionality I desired.