Creating a Google Page Rank Finder in Javascript
An interesting technology are Google Page Rank Finders. What they do is discover which result and page number a website is in Google's search results for a given term.
I thought an interesting implementation would be a completely client side one written in Javascript using Google's search API. To spoil the ending, after creating this I discovered the API only allows 8 results per page and 8 pages, making this useless if the site is beyond the 64th result, but the API is interesting and powerful regardless.
The finished version can be found at pagerank.red-stars.net with the complete Javascript.
Contents
google.search.WebSearch() object
The WebSearch() object is relatively simple, once instanced, all it needs is a call back to be setup before it can be used.
var webSearch = new google.search.WebSearch();
webSearch.setSearchCompleteCallback(this, searchComplete, null);
webSearch.execute("cookies");
The function searchComplete() will be called when the search for "cookies" completes. It's important that our instance of WebSearch named webSearch is inside of a scope which is viewable from searchComplete() because the callback is argumentless.
function searchComplete() {
// Make sure that there are results.
if (webSearch.results && webSearch.results.length > 0) {
var results = webSearch.results;
// Go through every result.
for (var resultIndex = 0; resultIndex < results.length; resultIndex++) {
var result = results[resultIndex];
// Show a messagebox with the results information.
alert(result.html.innerHTML);
}
}
}
We used the .html property from the result which gives us a Google-looking result. Now what if we wanted more than just the first page?
var currentPageIndex = 0;
function searchComplete() {
// Make sure that there are results.
if (webSearch.results && webSearch.results.length > 0) {
currentPageIndex++;
var results = webSearch.results;
// Go through every result.
for (var resultIndex = 0; resultIndex < results.length; resultIndex++) {
var result = results[resultIndex];
// Show a messagebox with the results information.
alert(result.html.innerHTML);
}
// Check if another page exists, if so, perform the request.
if (currentPageIndex < webSearch.cursor.pages.length)
webSearch.gotoPage(currentPageIndex);
}
}
The cursor object contains an array called pages who's length is used to determine the number of pages available. This will go through all available search results. When gotoPage is called, our call back function is once again executed when the search is finished.
A complete reference to the WebSearch and associate classes is available on code.google.com. The API is decent and flexible, if not limited in functionality.