execCommand(“insertHTML”, …) in Internet Explorer

后端 未结 4 1654
旧时难觅i
旧时难觅i 2020-12-06 06:23

I\'m building a wysiwyg-editor with an editable iframe using document.execCommand(). Now i need to use the \"insertHTML\" command which works perfe

相关标签:
4条回答
  • 2020-12-06 06:55

    I know this is extremely old, but since IE is still a problem, here is a better way which does not even use execCommand.

    This is missing some checks, like ensuring you're in the right container to be adding an image.

    var sel = window.getSelection();
    var range = sel.getRangeAt(0);
    var frag = document.createDocumentFragment();
    var img = document.createElement("img");
    // add image properties here
    
    frag.appendChild(img);
    range.insertNode(frag);
    
    0 讨论(0)
  • 2020-12-06 06:56

    In IE <= 10 you can use the pasteHTML method of the TextRange representing the selection:

    var doc = document.getElementById("your_iframe").contentWindow.document;
    
    if (doc.selection && doc.selection.createRange) {
        var range = doc.selection.createRange();
        if (range.pasteHTML) {
            range.pasteHTML("<b>Some bold text</b>");
        }
    }
    

    UPDATE

    In IE 11, document.selection is gone and insertHTML is still not supported, so you'll need something like the following:

    https://stackoverflow.com/a/6691294/96100

    0 讨论(0)
  • 2020-12-06 06:59
    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";
    };
    
    0 讨论(0)
  • 2020-12-06 07:14

    In case you haven't found anything yet,

    I had a button that would add html into an iframe, and was causing an error in IE8 when I clicked the button and no text was selected (i.e. when I had the blinking caret). It turned out that the button itself was getting selected (despite having unselectable="on"), and causing javascript to throw up the error. When I changed the button to a div (with unselectable on) it worked fine, in IE8 and FF.

    Hope this helps.

    0 讨论(0)
提交回复
热议问题