0

Is it possible to highlight text on a webpage and then examine the html with javaScript? (Let's say the javascript spits the HTML into another DIV)

I'm building an extension for chrome and I want to a user to be able to highlight text and I want the extension to be able to do two things: Copy that text (in an textarea/input or in span/div/any-element or examine the HTML of the selected text within a span/div/any-element.

This is all under the assumption that chrome has the ability to edit & examine the DOM. I believe this to be the case because of this warning I received in GC's extensions manager enter image description here This tells me that the extensions have some access. To at least the page address. Is there more access?

Keysle
  • 67
  • 8
  • Out of curiosity, what sort of examination of selected dom elements were you intending to carry out? – Jon Cram May 24 '12 at 14:01
  • I wanted the user to be able to highlight an element on the screen and have my extension periodically check if that element has changed. – Keysle May 30 '12 at 13:20

2 Answers2

0

Note: the following will not work in IE < 9. For a cross-browser solution, see HTML of selected text.

function getSelectionText() {
    var text = "";
    if (typeof window.getSelection != "undefined") {
        text = window.getSelection().toString();
    }
    return text;
}

function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            container.appendChild(sel.getRangeAt(0).cloneContents());
            html = container.innerHTML;
        }
    }
    return html;
}
Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
0

First of all, don't mind the warning Chrome gives for incognito mode. It's there just to warn people that when extension is enabled in incognito mode user man not be 100% safe that his browsing behavior will not be recorded (some evil extension may gather eg. bank access data).

If you want to catch the text that user selected in some textarea/input field you need to start with reading about and implementing content script in your extension. Such a script will be then injected by Chrome into websites of your choice. From there it can manipulate DOM and listen to events (just as regular scripts embeded into website).

For details about getting selected text see Tims answer to your question or simply search stackoverflow - this question was asked multiple times before.

Konrad Dzwinel
  • 36,825
  • 12
  • 98
  • 105
  • Sorry about asking a duplicate question. I searched it first, I must have just used the wrong set of words. – Keysle May 30 '12 at 13:20