3

I have the following method to paste some HTML at the caret position, using `range.insertNode(), sourced from this SO answer

function insertAtCursor(html) {
    var sel, range;
    if (window.getSelection) {
        // IE9 and non-IE
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();

            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ((node = el.firstChild)) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);

            // Preserve the selection
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } // non IE code removed
}

This is for a Windows Store app. I've discovered a bug in Universal Apps for Windows 8.1 where a serious typing lag occurs after a paste event using range.insertNode(). The issue only occurs in Windows 8.1 Universal Apps running under Windows 10. I can't replicate the issue under Windows 8.1 (although I definitely have experienced it in the past on Win8.1) - but it happens every time on Windows 10 on several machines using this sample app

https://onedrive.live.com/redir?resid=EE99EF9560A6740E!230777&authkey=!ACBcfSH4H1BE1s8&ithint=file%2czip

Does anyone know another way to paste HTML at the caret without using range.insertNode()? Windows Store apps using the IE11 rendering engine, so if it works in IE11 it will work in a Store App / Universal App

Community
  • 1
  • 1
roryok
  • 9,325
  • 17
  • 71
  • 138

1 Answers1

1

Doh. I feel kind of stupid now. The answer is the second answer from the link I posted

var doc = document.getElementById("your_iframe").contentWindow.document;

// IE <= 10
if (document.selection){
    var range = doc.selection.createRange();
        range.pasteHTML("<b>Some bold text</b>");

// IE 11 && Firefox, Opera .....
}else if(document.getSelection){
    var range = doc.getSelection().getRangeAt(0);
    var nnode = doc.createElement("b");
    range.surroundContents(nnode);
    nnode.innerHTML = "Some bold text";
};

When I replace my insertNode code with this surroundContents method instead, everything works. Now I just have to fork my preferred rich editor and replace the method

roryok
  • 9,325
  • 17
  • 71
  • 138