检索所选的单词

时间:2015-02-24 03:25:20

标签: javascript firefox-addon

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

1 个答案:

答案 0 :(得分:0)

我使用下面的函数在附加组件中获取所选文本。使用的方法取决于选择的位置和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();
    }
}