Snippets code from my daily experience

March 22, 2008

Get HTML code from nsISelection in XUL

Filed under: firefox,flock,nsISelection,selection,xul — dafi @ 9:56 am

Recently after a discussion with my friend bard we realized how it is easy to obtain HTML source code associated to the current browser (eg Firefox, Flock) selection.

It’s too simple to discuss the snippet, leave the code speaks itself

function selectionToHTMLSource()  {
    var sel = document.commandDispatcher.focusedWindow.getSelection();
    if (sel.rangeCount < 1) {
        return "";

    var node = sel.getRangeAt(0).cloneContents();
    var xmlStr = new XMLSerializer().serializeToString(node);
    return xmlStr;

The code handles single selection, if you need to work with multiple selections like tables rows/cells take a look at Table2Clipboard



  1. Thanks a lot dafi. You made my day 🙂

    Comment by Murali Bala — December 10, 2009 @ 6:10 am

RSS feed for comments on this post.

Create a free website or blog at

%d bloggers like this: