Javascript 为什么选定的文本不显示?
嗨,我的第一个插件有问题。。 我尝试使用此功能在网站页面上选择单词Javascript 为什么选定的文本不显示?,javascript,dom,firefox-addon,xul,add-on,Javascript,Dom,Firefox Addon,Xul,Add On,嗨,我的第一个插件有问题。。 我尝试使用此功能在网站页面上选择单词 function getSelected() { var userSelection; if (window.getSelection) { userSelection = window.getSelection(); } else if (document.selection) { userSelection = document.selection.createRange();
function getSelected() {
var userSelection;
if (window.getSelection) {
userSelection = window.getSelection();
} else if (document.selection) {
userSelection = document.selection.createRange();
}
return userSelection;
}
function getText() {
var select = getSelected()+ "";
alert(select);
}
在我的xul中,我以以下方式执行上述函数:
但是为什么我在页面上选择word时无法显示该单词(弹出窗口为空)可能发生的情况是,在XUL
上触发单击事件时,单击它的操作已经破坏了页面中的选择。尝试改用mousedown
事件(即将onclick
更改为onmousedown
)
另外,getSelected()
函数不必要地复杂。由于您的代码只需要在Firefox中工作,因此您可以使用:
function getSelected() {
return window.getSelection().toString();
}
window.getSelection()
返回chrome窗口中的选择,该窗口几乎总是空的。正如您所发现的,您需要使用document.commandDispatcher.focusedWindow
找出哪个窗口具有活动选择。(如果你很懒,你可能会尝试content.getSelection()
,但这只在页面没有框架时起作用。)@Tim Down:当我使用window.getSelection().toString()时,它仍然不起作用;但是当我尝试使用document.commandDispatcher.focusedWindow.getSelection().toString()时;而且它起作用了。为什么所选单词不能以第一种方式显示,而可以以第二种方式显示?@user495688您真的使用单一窗口吗?代码window==document.commandDispatcher.focusedWindow
打印的是真是假?@user495688:对不起,我不是Mozilla插件专家。一旦你掌握了页面的窗口
对象,我就开始工作了,但至于你是如何在附加组件中掌握它的,我不知道。如果document.commandDispatcher.focusedWindow
起作用,那么也许您应该使用它。。。
function getSelected() {
return window.getSelection().toString();
}