HTML5 Local Storage

Local storage allows the developer of a HTML5 webpage or app to store data locally on the client’s machine. Data stored in local storage will be persistent across browser and computer restarts. Local storage also has the bonus of being super easy to write to and read from. I have primarily being using local storage as part of a HTML5 game to store highscore, current Level and various other values that I want stored across sessions.

I have used JavaScript to manage all my local storage. An example of the data I want to store is as follows:

var saveData = {
	unlockLevel: 0,
	endlessHighScore: 0,
	goldCoins: 0
};

I hold all the data that I want to save in a single JavaScript struct so I am able to save all the data I want easily. By trying to load the data I can check if it already exists, If it does not exist I can save the initial values to the local storage. Notice that the data to be stored needs to be ‘stringified’. And data loaded needs to be ‘parsed’. The code below is what I am using in my upcoming Phaser game to save and load Game data to the local storage.

if(!localStorage.getItem("saveData")){
	localStorage.setItem("saveData", JSON.stringify(saveData));
	console.log("Could not load data, data store created")
}else{
	saveData = JSON.parse(localStorage.getItem("saveData"));
	console.log("Loaded Data")
}