views:

59

answers:

2

I want to write an extension for Google chrome that detects snippets of source code on web pages and automatically copies them to the clipboard.

I'm new to javascript and jquery, so for the first step, I wanted to try a very simple case.

Using this site as an example: http://www.swharden.com/blog/2010-03-05-realtime-fft-graph-of-audio-wav-file-or-microphone-input-with-python-scipy-and-wckgraph/

I want to find the element that contains the string "import " and add the text "Here is some code" after the element. Could someone give me a clue?

My first attempt was $('*:contains("import ")').after("Here's some code");, but that inserted after every element, including the parents, when I only want to insert after the lowest level child.

Edit: I want the code to work on any site. So I want to find any element that contains the "import ". Solutions specific to the example site aren't what I'm looking for.

A: 

works for me on your example site

$(".prettyprint span:contains('import')").after(" Here's some code");

make sure this code runs as a callback after the syntax prettifier is done

antpaw
Yeah, but I'd want to generalize this to other sites. I want to find any element that contains "import". The ".prettyprint" won't always be there.
Jesse Aldridge
A: 

Go through each text node on the page and search for the query - "import". If it matches, then append the string "Here's some code" after it's parent().

$("body *").contents().filter(function() {
    if(this.nodeType != Node.TEXT_NODE) {
        return;
    }
    if(this.nodeValue.indexOf('import') == -1) {
        return;
    }
    $(this).parent().after("Here's some code");
});

Using your given example, this will add "Here's some code" after each line of code. To find out where exactly the code begins, you will have to apply some heuristics.

Anurag