1

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

faressoft
  • 18,165
  • 42
  • 99
  • 142
  • 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
  • 306,503
  • 71
  • 443
  • 520