Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting HTML out of selection / range from a web page in Mozilla Firefox

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?

like image 964
Manish Chakravarty Avatar asked Jan 22 '23 20:01

Manish Chakravarty


1 Answers

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

like image 54
Xavi Avatar answered Feb 22 '23 22:02

Xavi