Skip to content Skip to sidebar Skip to footer

Retrieving A Word That Is Selected

I am writing a plugin which tries to display the meaning of a selected word in firefox browser. How do I capture the word/words being selected?

Solution 1:

I use the function below to get the selected text in an add-on. The method that is used depends on where the selection is and which version of Firefox. While which method to use could be selected based on those criteria, at the time I wrote/adapted it (and then updated it upon it breaking in Firefox 31.0), it was easier to just run through multiple methods until a valid string is obtained.

/**
 * 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();
    }
}

Post a Comment for "Retrieving A Word That Is Selected"