determine the frame id/name when a user has selected text in that frame- the page has multiple frames

前端 未结 1 1211
时光取名叫无心
时光取名叫无心 2020-12-22 11:27

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 t

相关标签:
1条回答
  • 2020-12-22 11:46

    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);
    
    0 讨论(0)
提交回复
热议问题