Firefox Extension: Get selected text

蹲街弑〆低调 提交于 2019-12-21 03:55:11

问题


I am working on a simple Firefox Extension and I want to get the selected text. I tried this:

var WordCount = {
    /* ... */
    changeSelected: function() {
        var selectedText = this.getSelection();
        var words = this.countWords(selectedText);
        this.changeStatus(words, " selected");
        //alert(selectedText);
    },
    getSelection: function(e) {
        var focused_window = document.commandDispatcher.focusedWindow;
        var sel_text = focused_window.getSelection();
        return sel_text.toString();    
    }
}
window.addEventListener("select", function(e) { WordCount.changeSelected(); }, false);

The Problem is, that I dont get the selection with document.commandDispatcher.focusedWindow.getSelection() and I don't know why :(


回答1:


Your problem is that document.commandDispatcher.focusedWindow is going to be pointing to a chrome window, where I suspect you actually want a content window. Try replacing that with content.getSelection()




回答2:


This works in firefox javascripting, so should be OK

window.getSelection().toString();

My guess is that document.commandDispatcher.focusedWindow fails




回答3:


Is this a normal Firefox extension or is it a JetPack Firefox extension.

In JetPack it would be

var doc = jetpack.tabs.focused.contentWindow;
if (doc.wrappedJSObject){ //This just checks if Firefox has put a XPCNativeWrapper around it for security
  win = doc.wrappedJSObject;
}

or you can just access the window directly with window.getSelection() like dcaunt suggested



来源:https://stackoverflow.com/questions/1138296/firefox-extension-get-selected-text

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