1

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

faressoft
  • 19,053
  • 44
  • 104
  • 146
  • possible duplicate of http://stackoverflow.com/questions/1877138/getting-selected-text-within-iframe-in-ie – cryo Sep 01 '10 at 08:22

1 Answers1

3

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
  • 318,141
  • 75
  • 454
  • 536