views:

332

answers:

1

Hello,

I currently using the following the get the selected text from a webpage into a custom firefox extension:

getSelectedText: function(){
    var textWindow = document.commandDispatcher.focusedWindow;
    var text = textWindow.getSelection();      
    if (text == null) {text =' ';}
    text = text.toString();
    text = text.replace(/^\s*$/ , "");
    text = text.replace(/\r/g, "\r");
    text = text.replace(/\n/g, "\n");
    text = text.replace(/^\s+|\s+$/g , " ");
    text = text.replace(new RegExp(/\u2019/g), "'");
    text = text.replace(new RegExp(/\u201A/g), ",");
    text = text.replace(new RegExp(/\u201B/g), "'");
    return {str:text};
}

This works just fine for plain text.

My problem is that i want all the elements of the webpage copied as well ( kind of like the webclips feature in safari )

Use case - If the user selects through a webpage with formatted text and images, I want the underlying HTML to get copied as well, so that I can accurately paste it into another XUL window - even send the contents as a rich HTML email if I so wish.

Any pointers?

+4  A: 

Try using this code:

var range = window.getSelection().getRangeAt(0);
var content = range.cloneContents();

After this code is executed, content will be a document fragment that contains a copy of the select DOM nodes. Note that event listeners will not be cloned. For more information go to https://developer.mozilla.org/en/DOM/range.cloneContents

Xavi
Thank you Xavi, this works for me!
Manish Chakravarty
works also on Chrome. Why wasn't this answer accepted?
jldupont