Wednesday, 16 September 2009

Cool ... iPhone handles the HTML5 onstorage event handler

… or in other words we can readily synchronise local browser storage with back-send server persistent storage. This is one of the fundamentals of compelling off line web applications.

So a little background. You may know that you can store data in your local browser database with javascript like …

function store() {
  if (window.localStorage) {
    var count=window.localStorage.getItem("count");
    if (!count) {
      count=0;
    }
    count++
    window.localStorage.setItem("count",count);
  }
}
window.onload = function() {
  store();
}

But this ain’t much good if you can’t get this data back to the server to do something useful with it, e.g. share with friends, share with your other devices, keep a backup, send a message … I could go on.

So what we really need is a way to easily listen out to storage events and deal with it in one place. Yep, we could create our own Javascript framework to do this and handle getters and setters, but that sounds nasty to me.

Instead we can know use the onstorage attribute on the HTML body tag to hook into a function that will handle all of these call backs based on local stored data.

function store() {
  if (window.localStorage) {
    var count=window.localStorage.getItem("count");
    if (!count) {
      count=0;
    }
    count++
    window.localStorage.setItem("count",count);
  }
}
function handleOnStorage() {
  myFunctionToSendDataToServer(event.key,
    event.newValue, event.oldValue);
}
window.onload = function() {
  document.body.setAttribute("onstorage", "handleOnStorage();");
  store();
}

Take a look at it in action in the bemoko mobile test suite. It works on iPhone 3 and Safari 4. You can even see the complete code here.