Wednesday, April 10, 2013

LocalStorage


LocalStorage works mostly as you expect it; it’s a simple key-value-store with a finite amount of storage, and once you hit that you get an exception. But we got a really wierd bug report from a user where he would browse to another site, and come back to the application to find that all of his settings and data were gone.

Turns out that under some circumstances, Android doesn’t load the localStorage data when you hit the back button. I’m guessing it has something to do with the fact that Android doesn’t always reload the page when you go back, it loads it from the browser cache (not the application cache) instead.

So to get around this Android bug, we set a persistent value in localStorage which we use as a check to see if localStorage is correctly loaded.


var check = "1234567890"
localStorage.setItem("android_check", check);

and when we want to fetch something from localStorage, we do:

var hasItem = function() {
  return (typeof localStorage[key] != "undefined" && localStorage[key] !== null);
}


var getItem = function(key, def) {
  if (!hasItem(key)) {
    if (localStorage.getItem("android_check") !== check) {
      // Reload the page so Android reloads localStorage
      window.location.reload();
    }
    return def;
  }
  return localStorage.getItem(key);
}

No comments:

Post a Comment