jQuery in Firebug: How and why?

There are a number of folks out there who use the Firebug extension for FireFox so they can debug webpages. Firebug also includes a Javascript console so you can execute arbitrary Javascript code against the current page.

If you're a fan of the jQuery library, there's a way you can use that in Firebug (first documented here):

var j = document.createElement("script");
j.onload = jsCallback;
j.src = "http://code.jquery.com/jquery-latest.pack.js";
document.getElementsByTagName("head")[0].appendChild(j);

See the line j.onload = jsCallback;? That fires a function called "jsCallback()" after jQuery is successfully loaded.

"Why a fancy callback?"

As I learned the hard way, if I were to just put Javascript code following the jQuery code, it might get executed before jQuery is successfully loaded, leading to errors. While I could just re-run the code (as jQuery would already be loaded), I was looking for a better solution to the problem, and this is what I came up with.

"So what can I do this callback?"

I'm glad you asked. One way using jQuery in Firebug comes in quite handy is if you want to dissect another web page. For example, let's say you want to run a Google search, and extract the URLs in the search results. Here's how to do it:

/**
* This is executed after jQuery is successfully loaded.
*/
function jsCallback() {
    
    var e = jQuery("a.l");

    var output = "";
    e.each(function() {
        output += jQuery(this).attr("href") + "\n";
    });

    alert(output);

}

var j = document.createElement("script");
j.onload = jsCallback;
j.src = "http://code.jquery.com/jquery-latest.pack.js";
document.getElementsByTagName("head")[0].appendChild(j);

"I could write $.get() calls to load Google's search results!"

Good luck with that. FireFox won't let you do that due to the same-origin policy.

"Well, how about if I get Google's search results in JSONP format?"

Um, good luck with that, too. You won't get very far without an HTTP referrer header, I'm afraid.

"So if I want to do this on an ad-hoc basis, I have to dissect the Google search results page?"

Yep, exactly.

Got any other tricks you find really useful to do with jQuery in Firebug? Let me know in the comments! 
 

2.285715
Average: 2.3 (7 votes)
Your rating: None