localStorage

Almost all games needs to record certain information about the player progression. For example, you may want to have a local leaderboard to track the player best results of each round, or the story progression, or the name of the player, etc. Sometimes is interesting to record these kind of information even after the user closes the browser and turn off the computer, thus, the next time a user comes back to your game, the progression is saved there.

HTML5 provides a feature for this kind of offline storage, called Local Storage. The concept is similar to cookies: you have a key-value storage system and you can write or read information locally with it. It is really basic, all you have to do is:

localStorage['key'] = 'value'

and you have an information stored in the user computer. The user can close the browser and turn off the computer but when he or she opens you game again, the information ‘key = value’ is still there.

The problem is when the browser does not support the HTML5 Storage feature. When this is the case, you need to use a third party library for offline storage, store the information into some server, or don’t save the information at all. The third option is the easier (if storing information is not essential), because you don’t have to change all your code, just define a stub localStorage object and the life goes on.

A beautiful way to detect if browser supports localStorage or any other HTML5 feature is using the Modernizr library. Thus, you can add the following verification to your code:

if (!Modernizr.localstorage) {
    window.localStorage = {};
}

Take a look at http://html5demos.com/storage to see an example.

Read more