Click here to Skip to main content
15,900,907 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a iframe embedded with html, I want to insert the text at specific cursor position inside this iframe. I tried with following java script code but no luck.


JavaScript
function getCaretCharacterOffsetWithin(element) {
    var doc = element.ownerDocument || element.document;
    var win = doc.defaultView || doc.parentWindow;
    var sel, range, preCaretRange, caretOffset = 0;
    if (typeof win.getSelection != "undefined") {
        sel = win.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(0);
            preCaretRange = range.cloneRange();
            preCaretRange.selectNodeContents(element);
            preCaretRange.setEnd(range.endContainer, range.endOffset);
            caretOffset = preCaretRange.toString().length;
        }
    } else if ((sel = doc.selection) && sel.type != "Control") {
        range = doc.selection.createRange();
        preCaretRange = doc.body.createTextRange();
        preCaretRange.moveToElementText(element);
        preCaretRange.setEndPoint("EndToEnd", textRange);
        caretOffset = preCaretTextRange.text.length;
    }
    return caretOffset;
}


The above code ideally return me the cursor position where I would place the text.

Thanks in advance
Posted
Comments
Nathan Minier 19-Nov-15 8:00am    
You're not going to be able to communicate between iframes. They are completely isolated from each other from a JavaScript point of view.

EDIT: This also applies to the page containing the iframe. The iframe is a black box as far as it is concerned.
Richard Deeming 19-Nov-15 9:30am    
If the parent and child documents are from the same origin, it's perfectly possible for one to call script methods and access the DOM of the other. You just need to use the contentWindow property on the iframe object.

Accessing the inner document | Frames and iframes | JavaScript Tutorial[^]
IFrame contentWindow Property | W3Schools[^]

The property is supported in all major browsers, and seems to go back as far as IE6.
Nathan Minier 19-Nov-15 9:43am    
Spiffy, I had no idea they'd changed that much.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900