0
votes

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

2

2 Answers

0
votes

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

0
votes

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