Javascript Firefox扩展:获取所选文本
我正在开发一个简单的Firefox扩展,我想获得选中的文本。我试过这个:Javascript Firefox扩展:获取所选文本,javascript,firefox,selection,Javascript,Firefox,Selection,我正在开发一个简单的Firefox扩展,我想获得选中的文本。我试过这个: var WordCount = { /* ... */ changeSelected: function() { var selectedText = this.getSelection(); var words = this.countWords(selectedText); this.changeStatus(words, " selected");
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()获得选择,我不知道为什么:(这在firefox javascripting中有效,所以应该可以
window.getSelection().toString();
我猜document.commandDispatcher.focusedWindow失败了这是一个普通的Firefox扩展还是一个JetPack Firefox扩展 在喷气式飞机上是这样的
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;
}
或者您可以直接使用dcaurn建议的
window.getSelection()
访问该窗口您的问题是document.commandDispatcher.focusedWindow
将指向一个chrome窗口,我怀疑您实际上想要一个内容窗口。尝试用content.getSelection()替换它
element.value.substring(element.selectionStart,element.selectionEnd);有效。我必须注意,我希望在文本区域中获取所选文本。这仅适用于selectionStart和selectionEnd。