Tue, 24 Feb 09

Gracefully Degrade the Google Custom Search Form So That It Works Without Javascript

It struck me a couple of nights ago that it wasn’t possible to search my site without Javascript, because of Google Custom Search’s reliance on Javascript. I’m not sure whether I just overlooked the fact or whether I’d realised that it was bad and ignored it. Either way, I decided it was time to do something about it. I stripped out the google custom search form and replaced it with a form that actually searches the google index of my site.

<form action='http://www.google.co.uk/search' id='searchForm'>
  <div>
    <input name='q' type='hidden' value='site:chrisroos.co.uk' />
    <input name='q' size='31' type='text' />
    <input name='sa' type='submit' value='Search' />
  </div>
</form>

So, the default behaviour (with javascript disabled) is now to search the content of my site in the google index. I then use javascript to progressively enhance the form to make it compatible with the google custom search. Done.

var googleCustomSearch = {
  createHiddenField : function(name, value) {
    var field = document.createElement('input');
    field.setAttribute('type', 'hidden');
    field.setAttribute('name', name);
    field.setAttribute('value', value);
    return field;
  },
  addHiddenField : function(form, name, value) {
    var field = this.createHiddenField(name, value);
    form.appendChild(field);
  },
  removeUnnecessaryField : function(form) {
    var elems = form.getElementsByTagName('input');
    for (var i = 0; i < elems.length; i++) {
      var elem = elems[i];
      if (elem.getAttribute('value') == 'site:chrisroos.co.uk') {
        elem.parentNode.removeChild(elem);
      }
    };
  },
  setupForm : function(form) {
    form.setAttribute('action', '/search');
    form.setAttribute('id', 'cse-search-box');
  },
  loadGoogleCustomSearchJavascript : function() {
    var externalScript = document.createElement('script');
    externalScript.setAttribute('type', 'text/javascript');
    externalScript.setAttribute('src', 'http://www.google.com/coop/cse/brand?form=cse-search-box&amp;lang=en');
    document.body.appendChild(externalScript);
  },
  init : function() {
    var searchForm = document.getElementById('searchForm');
    if (searchForm) {
      this.setupForm(searchForm);
      this.removeUnnecessaryField(searchForm);
      this.addHiddenField(searchForm, 'cx', '017216692514631406866:xbxiffq7rno');
      this.addHiddenField(searchForm, 'cof', 'FORID:9');
      this.addHiddenField(searchForm, 'ie', 'UTF-8');
      this.loadGoogleCustomSearchJavascript();
    }
  }
}
googleCustomSearch.init();