GetSelection not working for image in Chrome

On my site, I use the WYSIWYG editor, which uses an iframe.

When I select text with a double click to add a link to it, in Chrome, Safari and Firefox, the selected text is correct and the link is added.

However, when I click on the image, the selection is made only in Firefox. Chrome and Safari have an empty choice, and in order to select an image and add a link to it, I have to hover over it like a manual choice.

My code is:

 var sel = parent.document.getElementById('myframe').contentWindow.document.getSelection();

 if (sel.rangeCount > 0) {
    var range = sel.getRangeAt (0);
    var docFragment = range.cloneContents ();
    var tmpDiv = document.createElement ("div");
    tmpDiv.appendChild (docFragment);
    selHTML = tmpDiv.innerHTML;
 }

 if (selHTML != '') {
     parent.document.getElementById('myframe').contentWindow.document.execCommand(id,false,value);
 }

Is there any way to solve this problem?

Thanks in advance.

I am changing the code to one that matches @Tim's suggestions:

 var iframeWin = parent.document.getElementById('myframe').contentWindow;
 var iframeDoc = iframeWin.document;
 var sel = iframeWin.getSelection();
 var range = iframeDoc.createRange();
 var referenceNode = document.getElementsByTagName("img").item(0);
 range.selectNode(referenceNode);

 sel.removeAllRanges();
 sel.addRange(range);
parent.document.getElementById('myframe').contentWindow.document.execCommand(id,false,value);

But still does not work. Any other suggestions?

+3
source share
1 answer

, dblclick, , , WebKit.

Live demo: http://jsfiddle.net/x49hv/3/

:

var iframeWin = parent.document.getElementById('myframe').contentWindow;
var iframeDoc = iframeWin.document;

// Prevent errors in IE < 9, which does not support DOM Range and Selection
if (iframeWin.getSelection && iframeDoc.createRange) {
    iframeDoc.ondblclick = function(e) {
        if (e.target.nodeName.toLowerCase() == "img") {
            var sel = iframeWin.getSelection();
            var range = iframeDoc.createRange();
            range.selectNode(e.target);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    };
}
+1

All Articles