Finally, I stumbled upon a script that enables undo/redo functionality for programmatically inserted text. You can find it here.
If you want to check out the original script demo, click here.
Here is the initial script:
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// http://stackoverflow.com/a/9851769/529024
// Opera 8.0+
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
...
textarea {
padding: 10px;
font-family: Calibri;
...
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea name='textArea' class='textArea' rows="7" cols="50">Suspendisse convallis, metus ... viverra condimentum, neque neque tincidunt diam, nec vestibulum neque nisi...