Search code examples
javascriptfirefox-addonmozilla

Retrieve html code of selected text


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.


Solution

  • 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