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

扶醉桌前 提交于 2019-11-29 17:47:06

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!