0

I'm building a chrome extension and I need to read the HTML code of the current selection in background.html I can get the text selection from background.html:

function(info,tab) {
    var text = info.selectionText;
}

But I need the HTML code. From inside background.html I tried:

var selection = window.getSelection();
var range = selection.getRangeAt(0);
var container = range.commonAncestorContainer;
var html = container.innerHTML

But I believe I can't access the window object from inside background ...

I did read SpikeX post: Get page selection including HTML? but not couldn't find the source code he's referring to...

Thanks!

M

Community
  • 1
  • 1
Neurus
  • 657
  • 4
  • 27

2 Answers2

0

I have once written a user JavaScript for Opera inspired by the "view selection source" functionality from Mozila/Firefox. You can read about it and grab the code here.

Edit: Now when I read the question you linked I realized that I actually also wrote the first Chrome extension mentioned in the answer. It was also based on that script. However, it stopped working with some Chrome update and I never look into that issue. Nevertheless, it should be pretty easy to fix.

Jakub Roztocil
  • 15,930
  • 5
  • 50
  • 52
  • thanks jkbr - I read the code and I guess my problem is in this area: var sel = findSelection(window); ... anything I try including the aforementioned doesn't return anything on background.html. I believe that's my issue, I cannot get window.getSelection() from the background.html page - once I get that I know how to get the HTML using range .. – Neurus Feb 08 '12 at 03:59
0

You can access to html content with chrome.tabs.executeScript . See http://code.google.com/chrome/extensions/tabs.html

anfilat
  • 706
  • 4
  • 4
  • Thanks anfilat, I did that and it worked (injecting the JS from the background page) basically I had to add a listener and then inject the script: chrome.extension.onRequest.addListener(onSelection); chrome.tabs.executeScript(null, {file:"content.js",allFrames:true}); – Neurus Feb 11 '12 at 02:25