why the selected text not appear?
hi i have problem with my first addons.. i try to select the word on the website page with this function
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);
}
in my xul i execute the function above with this way :
<menuitem id="inlinetransContextMenuPage"
label="Terjemahkan dengan inlinetrans"
onclick="overlay.getText()" />
</popup>
but why i the word cannot appear when i select word on page (the pop up is blank)..
window.getSelection()
returns the selection from the chrome window, which is nearly always empty. As you discovered, you need to use document.commandDispatcher.focusedWindow
to find out which window has the active selection. (If you're lazy you might have tried content.getSelection()
but that only works if the page has no frames.)
Possibly what is happening is that by the time the click
event fires on the XUL <menuitem>
, the action of clicking it has destroyed the selection in the page. Try using the mousedown
event instead (i.e. change onclick
to onmousedown
).
Also, the getSelected()
function is needlessly complex. Since your code only needs to work in Firefox, you can use:
function getSelected() {
return window.getSelection().toString();
}
精彩评论