A bookmarklet highlighting Google’s results

A simple bookmarklet to highlight words on a page resulting of a Google query:

var gtc = '#000000'; var glc = new Array('#ffff66','#a0ffff','#99ff99','#ff9999','#ff66ff'); function init_google(){ var pat = /google\./i; if (pat.exec(document.referrer) != null){ var u_p = document.referrer.split('?'); if (u_p[1]){ var u_a = u_p[1].split('&'); for(var i=0; i<u_a.length; i++){ var kv = u_a[i].split('='); if (kv[0] == 'q'){ g_g(d_u(kv[1])); return; } } } } } function d_u(url){ return unescape(url.replace(/\+/g,' ')); } function g_g(te){ te = te.replace(/\"/g,""); var t_s = te.split(' '); var c = 0; for(var i=0; i<t_s.length; i++){ h_g(t_s[i], document.body,glc[c]); c = (c == glc.length-1)?0:c+1; } } function h_g(te, container, color){ var t_l = te.toLowerCase(); for(var i=0; i<container.childNodes.length; i++){ var node = container.childNodes[i]; if (node.nodeType == 3){ var data = node.data; var d_l = data.toLowerCase(); if (d_l.indexOf(t_l) != -1){ var n_n = document.createElement('span’); node.parentNode.replaceChild(n_n,node); var res; while((res = d_l.indexOf(t_l)) != -1){ n_n.appendChild(document.createTextNode(data.substr(0,res))); n_n.appendChild(c_n_g(document.createTextNode(data.substr(res,te.length)),color)); data = data.substr(res + te.length); d_l = d_l.substr(res + te.length); } n_n.appendChild(document.createTextNode(data)); } }else{ h_g(te, node, color); } } } function c_n_g(child, color){ var node = document.createElement('span’); node.style.backgroundColor = color; node.style.color = gtc; node.appendChild(child); return node; };init_google();

Given the length of the code, don’t expect it to work in Internet Explorer; for what it's worth, I only tested it under Mozilla. Provided you came on that page through Google, the simplest way to test if the bookmarlet works in your browser is to click on the link above.

Credits really go to Cal Henderson, whose code I simply reduced to put it in a more suitable format for a bookmarklet. Because of the format requirements, the copyright notice isn’t include in the code itself - hopefully the following is enough:

//
// google.js
// Google Highlighter
//
// Copyright(C)2001 - 2003
// Cal Henderson <cal@iamcal.com>
//
// Thanks to Ian Beveridge for bugfixes
//
// This code may be freely redistributed,
// providing this message remains intact.
//

The code was mainly reduced by using the following command line: cat google.js |sed -e s-//.*--|tr "\r\n\t" " "|sed -e "s/ */ /g"