views:

1170

answers:

2

I'm working on a Firefox extension that will manipulate highlighted text.

On a stand-alone page, I can get the selected text with:

selectedText = document.selection?document.selection.createRange().text;

Then I'd manipulate the selected text with string operations on the textarea in question. Unfortunately, that isn't possible for a plugin since I don't know where the user's selected text is.

Is there a way get the name of the element in which text is selected or to alter selected text without the name of the element?

A: 

you need to get the range object from your user selection:

var userSelection;
if (window.getSelection)
    userSelection = window.getSelection();
else if (document.selection)    // should come last; Opera!
    userSelection = document.selection.createRange();

var rangeObject = getRangeObject(userSelection);

...

function getRangeObject(selectionObject) {
    if (selectionObject.getRangeAt)
        return selectionObject.getRangeAt(0);
    else { // Safari!
        var range = document.createRange();
        range.setStart(selectionObject.anchorNode, selectionObject.anchorOffset);
        range.setEnd(selectionObject.focusNode, selectionObject.focusOffset);
        return range;
    }
}

...

The Range object has start and end container nodes, etc ..

more information can be found on Quirksmode here and on w3.org here

Scott Evernden
Thanks for the info. I tried putting those functions into my overlay.js, but couldn't manage to alert() out any highlighted text after installing the plugin.I'm a bit of a novice here, but is it possible that putting Safari and Opera code into a Firefox extension is the problem?
Mark Wilbur
+2  A: 

selectedText = content.getSelection().toString();

altblue
this doesn't answer his question and furthermore not all browsers support getSelection()
Scott Evernden
Hm, I read "I'm working on a Firefox extension..."
altblue
and to prove yourself in a dumb-simple way, open some random webpage in Firefox, select some text on that page, focus address-bar, paste "javascript:void(alert(content.getSelection()))" (without quotes), and press Enter.
altblue