【问题标题】:Retrieving a word that is selected检索选定的单词
【发布时间】:2015-03-01 19:51:39
【问题描述】:

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

【问题讨论】:

标签: javascript firefox-addon


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    • 2017-01-27
    相关资源
    最近更新 更多