title: Inserting HTML at cursors position and moving cursor to end of inserted html with javascript
body: <p>I am writing a script to insert presaved html content into Gmail's editable iframe in the compose page mentioned below. This script is only to be used in Greasemonkey on Firefox. So I don't need to consider any other browser.</p>
  
  <p>Currently it inserts the text once and then gets bugged. I guess because range.setStart() expects first parameter is a node, which createContextualFragment() does not return.</p>
  
  <p>Is there any other way to add html at current cursor's position and then move cursor to the end of the added html (not to the end of all content)?</p>
  
  <p><a href="https://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;source=mailto&amp;to=example@example.com" rel="nofollow">https://mail.google.com/mail/?view=cm&amp;fs=1&amp;tf=1&amp;source=mailto&amp;to=example@example.com</a></p>
  
  <pre><code>function insertTextAtCursor(text) {
      var sel, range, html, textNode;
      if (window.frames[3].window.frames[0].getSelection()) {
          sel = window.frames[3].window.frames[0].getSelection();
          if (sel.getRangeAt &amp;&amp; sel.rangeCount) {
              range = sel.getRangeAt(0);
              range.deleteContents();
              textNode = range.createContextualFragment(text);
              //textNode = document.createTextNode(text);
              range.insertNode( textNode );
              range.setStart(textNode, textNode.length);
              range.setEnd(textNode, textNode.length);
              sel.removeAllRanges();
              sel.addRange(range);
              window.frames[3].window.frames[0].focus();
          }
      }
  }
  </code></pre>
  
  <p>Update 1:
  If i comment the code to move the cursor after inserting html then its no longer bugged, but the cursor stays in the same place.</p>
  
  <pre><code>//range.setStart(textNode, textNode.length);
  //range.setEnd(textNode, textNode.length);
  sel.removeAllRanges();
  //sel.addRange(range);
  </code></pre>