Google Search Terms Highlighting for All Browsers #

One of the neat features of the Google Toolbar and of Google's cached pages is that they highlight for you the search terms that brought you there. Unfortunately the former is only available for MSIE, while the latter can destroy formatting, prevents scripts from working and present (slightly) outdated content. Inspired by the Highlighter Favelet (as pointed to by Bill Bumgarner), I've put together a slightly enhanced version that checks for a Google referrer, and in its presence hilights the search terms.

The short version: drag the Highlighter to your browser toolbar and click it after visiting a Google result (or any other time to specify other words to highlight).

The long version (expanded, more readable code follows): It uses the same color scheme as Google. I have preserved the scrolling to the first item found that the original favelet implemented, but it seems to overshoot (in Safari). I have only tested it in Safari and Firefox, but it is simple enough that it ought to work in all JavaScript DOM-supporting browsers. Quoted terms aren't handed properly (e.g. "Mihai Parparita" will be treated as two words, each with a quote on the left/right sides). It doesn't skip over common words that Google ignores (e.g. "is", "the"). Words are replaced blindly, so scripts may still stop working, button names may have HTML in them, etc. All of these are fixable problems, except that coding favelets beyond a certain length gets very annoying.

var items = new Array();

if (document.referrer.indexOf('google') != -1 &&
    document.referrer.indexOf('q=') != -1)
{
  var queryTermsRegExp = new RegExp('q=([^&]+)');
  if (queryTermsRegExp.test(document.referrer))
  {
    items = RegExp.$1.split('+');
  }
}

if (items.length == 0)
{
  var searchWords = prompt('Enter one or more words to highlight:','');
  items = searchWords.split(' ');
}

var colors = new Array('#ffff66', '#a0ffff', '#99ff99', '#ff9999', '#ff66ff',
                       '#880000', '#00aa00', '#886800', '#004699', '#990099');

b = document.body.innerHTML;

for (var i=0; i < items.length; i++)
{
  var replacementRegEx = new RegExp('(' + items[i] + ')','gi');
  
  b = b.replace(replacementRegEx,'<span style=\'background-color:' +
                                 colors[i % colors.length] +
                                 ';\'>$1</span>');
}

var scrollToRegEx = new RegExp('(' + items[0] + ')','i');
b = b.replace(scrollToRegEx, '<span id=\'scrollToHilight\'>$1</span>');

void(document.body.innerHTML = b);

window.scrollTo(0,document.getElementById('scrollToHilight').offsetTop);

Post a Comment