检索选定的单词

Retrieving a word that is selected

本文关键字:单词 检索      更新时间:2024-04-06

我正在编写一个插件,试图在firefox浏览器中显示所选单词的含义。如何捕获所选单词?

我使用下面的函数来获取附加组件中的选定文本。使用的方法取决于选择的位置和Firefox的版本。虽然可以根据这些标准选择要使用的方法,但在我编写/调整它时(然后在Firefox 31.0中崩溃时更新它),只需运行多个方法直到获得有效字符串更容易。

/**
 * Account for an issue with Firefox that it does not return the text from a selection
 *   if the selected text is in an INPUT/textbox.
 *
 * Inputs:
 *     win    The current window element
 *     doc    The current document
 *   These two items are inputs so this function can be used from
 *     environments where the variables window and document are not defined.
 */
function getSelectedText(win,doc) {
    //Adapted from a post by jscher2000 at 
    //  http://forums.mozillazine.org/viewtopic.php?f=25&t=2268557
    //Is supposed to solve the issue of Firefox not getting the text of a selection
    //  when it is in a textarea/input/textbox.
    var ta;
    if (win.getSelection && doc.activeElement) {
        if (doc.activeElement.nodeName == "TEXTAREA" ||
                (doc.activeElement.nodeName == "INPUT" &&
                doc.activeElement.getAttribute("type").toLowerCase() == "text")
        ){
            ta = doc.activeElement;
            return ta.value.substring(ta.selectionStart, ta.selectionEnd);
        } else {
            //As of Firefox 31.0 this appears to have changed, again.
            //Try multiple methods to cover bases with different versions of Firefox.
            let returnValue = "";
            if (typeof win.getSelection === "function") {
                returnValue = win.getSelection().toString();
                if(typeof returnValue === "string" && returnValue.length >0) {
                    return returnValue
                }
            }
            if (typeof doc.getSelection === "function") {
                returnValue = win.getSelection().toString();
                if(typeof returnValue === "string" && returnValue.length >0) {
                    return returnValue
                }
            }
            if (typeof win.content.getSelection === "function") {
                returnValue = win.content.getSelection().toString();
                if(typeof returnValue === "string" && returnValue.length >0) {
                    return returnValue
                }
            }
            //It appears we did not find any selected text.
            return "";
        }
    } else {
        return doc.getSelection().toString();
    }
}