Get page selection including HTML?

I am writing a Chrome extension and I was wondering if it is possible to get the selected text of a specific tab, including basic HTML? Therefore, if I select a link, it should also return the <a> tag.

I tried to look at the context menu event objects (yes, I use the context menu for this), and that is all that comes with the callback:

 editable : false menuItemId : 1 pageUrl : <the URL> selectionText : <the selected text in plaintext formatting, not HTML> 

It also returns a Tab object, but nothing in it was very useful.

So, I'm a little confused. Is it possible? If so, any ideas you might have would be great. Thank you :)

+7
google-chrome google-chrome-extension
source share
3 answers

It looks like this and this extensions do what you need.

-one
source share

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/

+8
source share

If you do not want all siblings, just the selected HTML, use range other methods, such as .cloneContents() (to copy) or .extractContents() (cut).

Here I use .cloneContents() :

 function getSelectedHTML() { var range = window.getSelection().getRangeAt(0); // Get the selected range var div = document.createElement("div"); div.appendChild(range.cloneContents()); // Get the document fragment from selected range return div.innerHTML; // Return the actual HTML } 
0
source share

All Articles