views:

34

answers:

1

How to get selected text from iframe (working on IE)

A: 

The following will work in all major browsers:

function getIframeSelectionText(iframe) {
    var win, doc = iframe.contentDocument;
    if (doc) {
        win = doc.defaultView;
    } else {
        win = iframe.contentWindow;
        doc = win.document;
    }

    if (win.getSelection) {
        return win.getSelection().toString();
    } else if (doc.selection && doc.selection.createRange) {
        return doc.selection.createRange().text;
    }
}

var iframe = document.getElementById("your_iframe");
alert( getIframeSelectionText(iframe) );
Tim Down