window.getSelection() Does Not Work When Run Via JSNI and On IE

157 views Asked by At

The following code works on Chrome and Firefox via JSNI and on all browsers in pure JavaScript, but not on IE via JSNI.

GWT JSNI:

    // windowEl is the contentWindow of an iframe
    protected native Element insertImage(String src, String title, String cssClassname, Element windowEl)
    /*-{
         var result = null;
         var selRanges = windowEl.getSelection();   // no ranges returned here on IE
         if (selRanges.rangeCount > 0) {
             var curRange = selRanges.getRangeAt(0);
             if (curRange.toString().length == 0) {
                 var imageNode = windowEl.document.createElement('img');
                 imageNode.src = src;
                 imageNode.alt = title;
                 imageNode.title = title;
                 imageNode.className = cssClassname;
                 curRange.insertNode(imageNode);
                 result = imageNode;
             }
         }
         return result;
     }-*/;

JavaScript:

 var myIframe = $doc.getElementById('my_iframe');
 var range = myIframe.contentWindow.getSelection().getRangeAt(0);
 var imageNode = myIframe.contentWindow.document.createElement('img');
 imageNode.src = 'goo.gl/Zun4LD';
 imageNode.alt = 'error';
 imageNode.title = 'error';
 imageNode.className = 'my_css_class';
 range.insertNode(imageNode);

The problem occurs when getSelection() returns nothing on IE when run via JSNI.

I am using GWT 2.7 & IE 10 to test.

Any ideas why this might be happening? Is this a bug with GWT 2.7?

1

There are 1 answers

0
Benjamin Leclerc On BEST ANSWER

Make sure that your iframe's contentWindow is not losing focus. IE can't deal with these situations as elegantly as others.

Try:

// windowEl is the contentWindow of an iframe
protected native Element insertImage(String src, String title, String cssClassname, Element windowEl)
/*-{
     var result = null;
     windowEl.focus();  // ***** add this to be sure you're not losing focus
     var selRanges = windowEl.getSelection();   // no ranges returned here on IE
     if (selRanges.rangeCount > 0) {
         ...
     }
     return result;
 }-*/;