jeudi 5 février 2015

Playing with localStorage and IE8

I played with localStorage JavaScript API the other day. It allows you to store persistent data, associated with a web site inside your browser. The cool thing is that it is a HTML 5 API compatible with IE8 (which is still the standard at work).

On modern browsers, you can use it on plain html files, even if they're not served by a http server. That's convenient if you want to build something that can be downloaded and use offline. IE8 cannot do that: you need to have you files served by a http server to make localStorage work. If you have Python 3 installed (and you should!), you can serve file painlessly using http.server module from command line:

python -m http.server 8000

You can then connect to http://localhost:8000 and enjoy.

Another nasty stuff that can bite you: IE8 doesn't want you to store undefined values in the local storage. To avoid headache, use it like this:

localStorage.setItem("itemKey", varThatCanBeUndefined || "");

This way, if varThatCanBeUndefined is undefined, the value associated with itemKey will be an empty string. Ugly but it works.

The irony for me is that the concerned piece of code do not work since it is encapsulated in a web site that force IE7 compatibility. Therfore, all my work to make it compatible with IE8 is useless, and I have been forced to add a fall back for localStorage object:

storage = localStorage || { 
   setItem: function(item, value) {}, 
   getItem: function(item) { return "" } 

However, the test worth it: I have it to work on Firefox and it was the occasion to play with this nice feature and to write this article!