Is it possible to insert text into textarea and update the undo / redo queue?

A few days ago, I posted a question on how to update text in Internet Explorer. As it turned out, the method used also does not work in Firefox.

This made me wonder if there is a way to change the value of the text field and update the undo / redo queue (calling ctrl-Z or document.execCommand('undo'); )

So far I have found two possibilities, but they do not work in all browsers:

Option 1:

 var event = document.createEvent('TextEvent'); event.initTextEvent('textInput', true, true, null, text, 9, "en-US"); textarea.focus(); textarea[0].setSelectionRange(selection.start, selection.end); textarea[0].dispatchEvent(event); 

Note. It doesn't seem to work in IE (in general) and Firefox

Option 2:

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

It does not work in IE (tested under 9, but does not seem to be implemented at all), I do not know other browsers.

+6
source share
3 answers

The solution I came up with is the one, but I'm open to more complex ideas:

I am checking for insertText through document.queryCommandSupported. If it exists, I use it. If not, I just replace the text:

 var text = "hello world", textarea = jQuery("textarea"), selection = {'start': textarea[0].selectionStart, 'end': textarea[0].selectionEnd}; if (document.queryCommandSupported('insertText')) { document.execCommand('insertText', false, text); } else { textarea.val(textarea.val().substring(0, selection.start) + text + textarea.val().substring(selection.end, textarea.val().length)); } 
+5
source

Option 1 works well (8/19/2016), but is deprecated in Chrome for one of the future releases. Sending an event generates the following warning:

A DOM event generated using JavaScript triggered a default action in the browser. This behavior is non-standard and will be removed in M53 around September 2016. See https://www.chromestatus.com/features/5718803933560832 for more details.

+2
source

It seems that today all modern browsers support your option # 1, dispatchEvent. See here for more details:

http://help.dottoro.com/ljrinokx.php

0
source

Source: https://habr.com/ru/post/957509/


All Articles