10

我正在开发一个简单的 Firefox 扩展,我想获取选定的文本。我试过这个:

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);

问题是,我没有使用document.commandDispatcher.focusedWindow.getSelection()获得选择,我不知道为什么:(

4

3 回答 3

10

您的问题是它将document.commandDispatcher.focusedWindow指向一个 chrome 窗口,我怀疑您实际上想要一个内容窗口。尝试将其替换为content.getSelection()

于 2009-07-16T17:51:58.017 回答
1

这适用于firefox javascripting,所以应该没问题

window.getSelection().toString();

我的猜测是 document.commandDispatcher.focusedWindow 失败

于 2009-07-16T15:16:45.927 回答
0

这是一个普通的 Firefox 扩展还是一个 JetPack Firefox 扩展。

在 JetPack 中它会是

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;
}

或者您可以直接使用window.getSelection()dcaunt 建议的方式访问窗口

于 2009-07-16T15:36:51.613 回答