Log in

27 November 2010 @ 04:05 pm
Pre-populate the search box on your 404 page with words from the bad url  
I'm not the first to come up with this idea, but I still had to spend an hour or so figuring out how to do it. What is the internet for?!

First, build your custom 404.shtml page, and paste your google search bar code into it (sign up for google's webmaster tools and/or adsense to get this part.)

After the search bar code, paste this:

<script type="text/javascript">
var badURL = "<!--#echo var="REQUEST_URI" -->";
var search = badURL.replace("/","");
search = search.replace(/\//g," ");
search = search.replace(/\..*/,"");
document.getElementsByName("q")[0].value = search;

And you're done!  Here's how it works:

Suppose someone misremembers how my site works and tries to browse to "http://www.heyweiner.com/stories/chairlift.html". The webserver will respond with the 404 page, and insert "/stories/chairlift.html" in the first line of the script.  The following lines strip out the opening "/", then replace any subsequent slashes with spaces (if your URLS often use other characters, such as underscores, to represent spaces, you'll want to expand the regex to turn those into spaces too.)  The final replace strips out the file extension at the end.  Then, the last line adds the resulting string, "stories chairlift" into the google bar.  Here's the result:

You could add a line to automatically press the button, but it's probably not a good idea.  Google might take a dim view of it, and you want your visitor to have the opportunity to edit the search terms.

Hope this helps.