Getting selected page text is pretty simple, you can do something like
var text = window.getSelection().toString();
and you will get a textual representation of the currently selected text, which you can transfer from the contents of the script to a wallpaper or popup.
Getting HTML content is much more difficult, mainly because the selection is not always on the clean border of the HTML in the document (which is if you select only a small part of a long link or a few table cells for example). The most straightforward way to get all the html associated with the selection is to bind the commonAncestorContainer, which is a property in the selection range that corresponds to the deepest node, which contains both the beginning and the end of the selection. To get this, you would do something like:
var selection = window.getSelection(); // Only works with a single range - add extra logic to // iterate over more ranges if needed var range = selection.getRangeAt(0); var container = range.commonAncestorContainer; var html = container.innerHTML
Of course, this most likely contains a lot of HTML that was not actually selected. Perhaps you can iterate over children from a common ancestor and cut out everything that was not in your choice, but it will be a little more complicated and may not be needed depending on what you are trying to do.
To show how to do all this in an extension, I wrote a short sample that you can specify: http://github.com/kurrik/chrome-extensions/tree/master/contentscript-selection/
Arne Roomann-Kurrik
source share