Retrieve html code of selected text

308 Views Asked by At

In mozilla, I can select a text and print the selected text using contentWindow.getSelection(). But I am trying to get the underlying html code block for this selected text. Is there any way I can retrieve it?

I need to extract urls and other informations like src, etc. underneath any clickable text that a user selects. I need the code block of its parent node.

Thanks.

2

There are 2 best solutions below

5
On BEST ANSWER

Do you have a mouse event listener or something before you do contentWindow.getSelection?

If you do you can get the selected node by doing:

    function onMouseUp(event) {
        var aWindow = event.target.ownerDocument.defaultView;
        // should test if aWindow is chrome area or actually content area
var contentWindow = aWindow.document instanceof Ci.nsIHTMLDocument ? aWindow : null; // i guessed here but testing if its content window is done in some similar way
if (!contentWindow) { return }
        // do contentWindow.getSelection im not familiar with the code, if selection exists // check if more then one range selected then get node for each, however im going to assume only one range is selected
        var nodeOfFirstRange = event.explicitOriginalTarget
        var elementOfNode = nodeOfFirstRange.parentNode;
        var htmlOfElement = elementOfNode.innerHTML;
    }

    Services.wm.getMostRecentWindow('navigator:browser').gBrowser.addEventListener('mouseup');

issue with this code is if user mouses down in content window and then highlights and mouseup while mouse its outside of content window, like on chrome window or even outside the browser (like if the browser window was not in maximum or if user mousedup in taskbar of os etc) so just use this code as a guide

2
On

Retrieving the HTML should be relatively easy, but it depends on what you are wanting. window.getSelection() returns a selection object. You can use:

  • window.getSelection().anchorNode to obtain the Node in which the selection begins and
  • window.getSelection().focusNode to get the Node in which the selection ends.

For instance:

let selection = contentWindow.getSelection();
let firstElement = selection.anchorNode;
let lastElement = selection.focusNode;

What you do once you have the nodes/elements will depend on what it is that you are actually wanting to find. You have not specified that, so manipulating it past finding those nodes would just be a guess as to what you are wanting. For instance, you just might want to find the parent of the anchorNode, verify that it contains the focusNode (firstElement.parentNode.contains(lastElement)) (if not then continue finding the next parent until it does) and use the parent's innerHTML. Alternately, maybe you want to find the first parent element of the anchorNode which contains the focusNode and then use a TreeWalker to walk the DOM tree until you find the anchorNode and start accumulating the HTML until you encounter the focusNode.