0

I have a scenario in which there are multiple iframes/frames open in one web page. Now user may select some text in any one of the open frames/iframes. I want to determine the id/name of the iframe in which user has selected text, using the iframe id/name I will then do some operations on the selected text.

How do I do this?

Arvind
  • 6,404
  • 20
  • 94
  • 143

1 Answers1

1

This will get the first iframe in the curent document that has a non-empty selection. If an iframe is from another domain and hence inaccessible to JavaScript running in the current document, the selection cannot be retrieved and the iframe is ignored.

function getSelectedText(win) {
    var sel;
    if (win.getSelection) {
        return "" + win.getSelection();
    } else if ( (sel = win.document.selection) ) {
        if (sel.type == "Text") {
            return sel.createRange().text;
        }
    }
    return "";
}

function getIframeWithSelection(win) {
    var iframes = win.document.getElementsByTagName("iframe");
    for (var i = 0, len = iframes.length, selectedText; i < len; ++i) {
        try {
            selectedText = getSelectedText(iframes[i].contentWindow);
            if (selectedText != "") {
                // alert just there for debugging
                alert(selectedText);
                return iframes[i];
            }
        } catch (e) {}
    }
    return null;
}

// Example
var iframe = getIframeWithSelection(window);
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • this is a good solution if only Arvind did some searching and found your tim-down's other answer witch is much based on the same question http://stackoverflow.com/questions/1471759/how-to-get-selected-text-from-iframe-with-javascript – david Oct 18 '11 at 14:33
  • @TimDown- I am trying to use your function (as given above) in a google chrome extension- the problem is that in that extension, your function is loaded into a 'background page'. Is there some way to specify the window (within which iframes have to be checked?)... Maybe pass the title of that main window as a parameter to your function, so that your function then looks for iframes in the window which has specified title? Or some other way? Thanks... – Arvind Oct 23 '11 at 05:53
  • @Arvind: I've done nothing with Chrome extensions, but there was a small error in the code, which I've now corrected: it now looks for iframe elements only within the window specified (`win`). Does that help? – Tim Down Oct 23 '11 at 09:35
  • @TimDown- I changed the chrome extension- i used the js file containing your code as part of a content script (this is injected directly into the page)- that did the work I wanted... Thanks! – Arvind Nov 04 '11 at 14:04