Using HTML5 Web Storage in Drupal 7

html5

There are a bunch of ways to store data on the client side including cookies, jquery data and HTML5 Web Storage. The problem with using cookies is that if you are trying to do any sort of high performance implementation of Drupal with Varnish, using cookies is not an option because its a cache buster. So enter HTML5 Web Storage. Web storage is supported in Internet Explorer 8+, Firefox, Opera, Chrome, and Safari but not IE 7 or previous versions. I realize that IE7 can still account for a significant portion of a website's traffic but I only develop for IE8 and up. Lets face it, half of the Internet is dysfunctional if you use IE7 or lower, its time to upgrade your browser.

I am working on a project with Apache Solr, Search API and spatial, location based searches. I'd like to keep the most recent search string in the form and retain this for a user's session. It might even be nice to keep a history of searches for the user but I don't want to store this on the server because of the Varnish issue and I don't really care all that much.

With HTML5 Web Storage, this is really, really easy:

(function($) {
  Drupal.behaviors.my_module_name = {
    attach: function (context, settings) {
       $(function(){
         $('#my-search-form').submit(function(){
             // add search value to Web Storage
             sessionStorage.setItem('search', $('#edit-search').val());
        });
        if (sessionStorage.getItem('search')) {
          // get search value from Web Storage
          $('#edit-search').val(sessionStorage.getItem('search'));
        }
      })
    }
  };
})(jQuery);

This is just a really simple example of how easy it is to use web storage with the sessionStorage. You can also use localStorage which persists longer than a session. Replace "my_module_name" with your theme name or module name and then put this into a .js file that is included in your theme or module. Replace #my-search-form with the div id of your form and #edit-search with the div id of the search text box of your search form.