Hack #56. Highlight Search Terms

When you click through to a page from a search engine, highlight the terms you originally searched for.

Have you ever searched for something on Google, then clicked through to a page and been unable to figure out why this page ranked so highly? Not only does it seem irrelevant, you can't even find the keywords you originally searched for! This hack tracks your search engine clickthroughs and highlights your original search keywords when you leave the results page for a given hit.

The Code

This user script runs on all pages except Google search result pages. The code is divided into three parts:

  1. The highlightWord function walks the DOM tree recursively and calls itself with each node, and then checks whether the current node is a block of text that contains a specific search term. If so, it wraps the word in a span tag and styles it with CSS to display with a yellow background.

  2. The highlightSearchKeywords function looks at the page you came from (document.referrer). If you came from a search results page, it parses out the keywords you originally searched for and calls highlightWord with each keyword.

  3. Finally, we add an event listener that calls highlightSearchKeywords after the page has completed loading.

Save the following user script as searchhi.user.js:

	// ==UserScript==
	// @name		 Search Highlight
	// @namespace    http://www.kryogenix.org/code/
	// @description  highlight search terms when coming a search engine // @include * // @exclude http://www.google.tld/search* ...

Get Greasemonkey Hacks now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.