Web storage explained using a Tic Tac Toe Game

Introduction

Web storage is a mechanism for storing data permanently in a web browser.It is one of the HTML5 features. As per the W3C® specification web storage APIs can store date in key-value pair. There are two types of web storage, the first one is local storage and the second one is session storage. Details of each storage mechanism have been covered in the coming sections.   Web storage data is private to each application and cannot be accessed by other applications. For demonstrating the usage of session storage and local storage the simple Tic-Tac-Toe application has been used in this article.

How to set, get and delete data for one session using sessionStorage

The sessionStorage object stores data only for one session. i.e.: when you close your application, the session will expire and session Storage object values will be lost.   We can set key value pair by using the setItem(mykey, myvalue) method as given below. The first argument is unique key and the second argument is the data.  

// syntax to set data
 sessionStorage.setItem(yourkey, yourvalue);

Once data is set, you can get data by using the getItem(mykey) method. Here,’ yourkey’ is the unique key which is used to get data.

// syntax to get data
var getdata = sessionStorage.getItem(yourkey);

If you want to set your name, you can use the code given below. Here ‘yourname’ is the unique key as thefirst argument and Ram is the data asthe second argument.

// use below line of code to set your name
sessionStorage.setItem('yourname', 'Ram');

To get your name, you can use the code given below.

// use below line of code to get your name
var yourname = sessionStorage.getItem(' yourname ');

Now if you want to delete particular data from session storage, you can use the removeItem(yourkey) method.

// delete data from sessionStorage
var removename = sessionStorage.removeItem(yourkey);

Sometimes, we might need to delete all data from current session. In this case, we can use the clear() method. ;

// To delete all data from current session use below line of code
sessionStorage.clear();

You can also store your name for one session as follows.

sessionStorage.yourname = "Sahu";

How to set, get and delete data using localStorage

The localStorage object provides a storage variable to store data. When you store data on local storage variable this data is saved permanently in local storage. Even if you close the application, the data will be available in local storage variable.We can use all methods in localStorage as explained in the sessionStorage chapter. The only difference is that if you close your application then all data will still be available. When we use the clear() method with local storage, all local storage data will be deleted. Using below line of code you can set key value pair in local storage using setitem method. Where ‘yourkey’ is the unique key which is used to get data.        

// syntax of set data
localStorage.setItem(yourkey, yourvalue);

To retrieve data, you can use the getitem(yourkey) method and store it in the getdata variable as follows.

// How to get data
var getdata = localStorage.getItem(yourkey);

Here an example is given showing how to store your name using the setItem method.        

// use below line of code to set your name
localStorage.setItem(' yourname', 'Ram');

To get your name, you can use below line of code.

// use below line of code to get your name
var yourname = localStorage.getItem(' yourname ');

If you want to remove data from localstorage, use the removeItem(yourkey) function.

// delete data from localStorage
var removename = localStorage.removeItem(yourkey);

Below code is used to delete all data from localstorage.

// To delete all data from localStorage use below line of code
localStorage.clear();

Now with Tic-Tac-Toe example let’s see how we can use session storage in an application.

Using session storage in Tic Tac Toe game

Here player’s name and score of the game is stored in the sessionStorage object.

Figure1:Sessionstorage

Code example

You can check whether your name is empty or not by using the function saveplayername(). If your name is empty then it will display alert message. Once you enter your name, click on the button (save name and start game) to play the game. This button will load TIC TAC TOE game. In this game, your turn will be always first with symbol “X” and the next turn will be device’s with symbol “O.

Here we are storing player name in sessionStorage object.

function savePlayerName()
{
	var username1 = $('#Player1').val().trim();
	var username2 = $('#Player2').val();
	// check your name, if it is empty then it display alert message
	if (!username1)
	{
		alert("Please enter your name");
		return;
	}
	//save a name value
	sessionStorage.setItem("Player1name", username1);
	sessionStorage.setItem("Player2name", username2);
	// Initialize score of the game
	sessionStorage.Player1Score = 0;
	sessionStorage.Player2Score = 0;
	window.location.href="#play-game-page";
}

Using ‘sessionStorage’ variable you can access session storage. Below code checks who the winner of the game is in this session. If session expires, the score of the player is lost. Both players’ score is kept in the sessionStorage object.       

//The TicTacToeWinnner(symbol) used to check who is winner of the game.
//In this function we increment the score of the player.
function TicTacToeWinnner(symbol)
{
	var matchwin = [ [ 0, 1, 2 ], [ 3, 4, 5 ], [ 6, 7, 8 ],
	                 [ 0, 3, 6 ], [ 1, 4, 7 ], [ 2, 5, 8 ],
	                 [ 0, 4, 8 ], [ 2, 4, 6 ] ];
	for ( var a = 0; a < matchwin.length; a++)
	{
		if (CanvasContent[matchwin[a][0]] === symbol &&
			CanvasContent[matchwin[a][1]] === symbol &&
			CanvasContent[matchwin[a][2]] === symbol)
		{
			var name;
			var newScore = 0;
			if (symbol === 'X')
			{
			name = sessionStorage.getItem("Player1name");
			//increment score for your name
			sessionStorage.Player1Score = Number(sessionStorage.Player1Score) + 1;
			newScore = sessionStorage.Player1Score;
			}
			else
			{
			name = sessionStorage.getItem("Player2name");
			//increment score for mobile
			sessionStorage.Player2Score = Number(sessionStorage.Player2Score) + 1;
			newScore = sessionStorage.Player2Score;
			}
			// Display winner player name
			$("#Winner-player").html("Current winner Name :"+ name);

			restartGame();
			for ( var l = 0; l <= 8; l++)
			{
			positiondata[l] = true;
			}
 			// check if there is top score or not.
                        if(localStorage.highScore)
         		{
                        // If player score is greater-than top scorer then
                        // update its score as a top scorer.
 	                    if(newScore > localStorage.highScore)
			    {
				setHighScore(name, newScore);
			    }
			}
			else
			{
				setHighScore(name, newScore);
			}
			return true;
		}
	}
	return false;
}

Using local storage in Tic Tac Toe game

Here localstorage is used to store high score of the game so that even if you exit the game, the high score of the game will be available.

The screen shot from emulator is given below for local storage data.

Figure2: Weblocalstorage

Code example

If a player is able to score more than the current top score, his name and score will be updated as the top scorer.Player gets an alert message asking whether to save the new high score. If a player doesn't want to store his/her name then he can click on cancel button.

Here we use localStorage object to update and keep the high scorer name and its record permanently.         

//check player score, if it is higher then top score then update top scorer name
function setHighScore(name, newScore)
{
	var res = confirm("This is a new high score. Do you want to save this score ?");
	if (res === true)
	{
		//save the winner score and name to local storage
		localStorage.highScore = newScore;
		localStorage.highScorerName = name;
	}
}

Below code is used to get the top scorer name and its score. To display top score click on the top score button. Here localStorage object is used to store score data permanently.          

//The function showtopscore() display top scorer name and its score.
function showTopScore()
{
	// If there is top score then display its name and score.
	if(localStorage.highScore)
	{
		var msg = "Top scorer name : " + localStorage.highScorerName +
                          " Score : " + localStorage.highScore;
		alert(msg);
	}
	else
	{
		// if there is no top score then it will display
                // alert message for example  "No top score"
		alert("No top score");
	}
}

How to delete high score data

The high score of this game is saved in localStorage. If a player wants to delete the high score data then he can click on clear score button and it deletes data from localStorage. When the clear score button is clicked, the following function is called.        

// To delete High score of the game use below function
function clearScore()
{
	var res = confirm("Do you want to clear the score ?");
	if (res == true)
	{
		localStorage.clear();
	}
}

Conclusion

In this article we learnt how to use local and session web storage in Tizen web application. You can use the sample application as a reference when using web storage in your application.

Build Requirements

The application is built for devices with Tizen 2.0 firmware.

SDK Environment used: 2.0.0a4

Appendix

Sample app attached.

File attachments: