HTML5 Guidelines for Web Developers

(coco) #1

228 Chapter 8—Web Storage and Offline Web Applications


The timestamp ts is the time in milliseconds since 1.1.1970. Now that the values
are saved in localStorage, you can give appropriate feedback to the user if the
user tries the game again:

// get collected data
var games_done = [];
var max_percent = 0;
for (var i=0;i<localStorage.length;i++) {
var key = localStorage.key(i);
if (key.substring(0, 9) == "click2tick") {
var item = JSON.parse(localStorage.getItem(key));
if (item.gid == game.store.gid) {
games_done.push(item);
max_percent = Math.max(max_percent, item.percent);
}
}
}

// show collected data
var s = '';
if (games_done.length == 0) {
s += 'You have not played this game before.';
}
else {
s += 'You have played this game '+
(games_done.length+1)+' times<br>';
s += 'Your best hit rate till now: '+
max_percent+"%\n";
}
_get('localStorage').innerHTML = s;

The for loop runs over all items found in localStorage. For each element, the key
is determined and checked if it starts with the string click2tick. This check en-
sures that any elements saved by another application of this website are skipped
in localStorage.
We then use the JSON.parse function to convert valid elements into JavaScript
objects. If the game ID matches the ID of the current game (item.gid == game.
store.gid), the object is added to the array games_done and checked if its hit rate
is higher than the highest previous one (Math.max). A string s is then assembled,
giving details on the number of games played and the maximum percentage. As
you can see in Figure 8.5, the game also indicates whether the browser is online
or offline. This is relevant for our application because the player cannot look for
new games and updates while in offline mode:

var setOnlineStatus = function() {
if (navigator.onLine) {
_get('onlineStatus').innerHTML = 'Online';
_get('onlineStatus').className = 'online';
Free download pdf