10 - Phonegap Data Storage - Session Storage


Every time, you might not need data on a permanent basis. There could be some situations where you need data only for a particular session. For example, you are developing a game app and you want to store the level the player completed. This value might get updated frequently as the player goes from one level to another level. You might not require the level details once the player quits the game. Similarly, you might have to address a user who logged into the app until he logs out. You can use sessionStorage in such situations. The data stored in sessionStorage will be available only for that particular session and will be lost once the user closes the application.

sessionStorage Object

The sessionStorage object also has the same three methods that the localStorage object has: setItem, getItem and removeItem. Suppose, we use the same project that we created in the local storage tutorial and try to store the same data in session. Then, we will have to replace localStorage with sessionStorage. In other words, the only difference will be instead of window.localStorage.setItem, we will write window.sessionStorage.setItem. Same is the case with getItem method. In the localStorage tutorial, we stored and retrieved single values. This time, let's create an app that store an array in the session. We will store the array as a string in the session storage and redirect the user to a new screen on the click of a button and then retrieve the values in the array as soon as the page is loaded.

Create an App

Assume that we are developing a game app where the user has to enter his first name, last name and select the type of game he wants to play and also the difficulty level. Once the user enters these details and clicks the Enter button, we will display a welcome message using the information entered by the user. In a real app, the situation might be different. The first name and last name could be used to address the user and the type of game and difficulty level could be used to display the available games of that particular type and of the particular difficulty level. As this project is for the purpose of understanding session storage, we just display a welcome message.

So, first create a mobile app for Android platform. Create a project named AndroidSessionStorage on the desktop. Once the project is created on the desktop, bring the project into the Android Development Environment (Eclipse). Open the index.html file in the assets/www folder using your text editor and clean it up. You can also change the title.

Our app needs to have two textboxes for the user to enter his first name and last name and two drop downs to select the type of game and difficulty level. We also need a button on the click of which we will first store the array in the session and then redirect the user to a new page where we will display the welcome message. So, add the following lines of code inside the <body> section of index.html file.

Add the following line inside the <body> tag.

First Name:<input type="text" id="fname" /><br />
        Last Name:<input type="text" id="lname" /><br />
        The type of Game you Like:
        <select id="type">
         <option value="advent">Adventure</option>
         <option value="racing">Racing</option>
         <option value="puzzle" selected>Puzzle</option>
         <option value="coord">Coordination</option>
        </select><br />
        Choose Difficulty Level:
        <select id="difficulty">
            <option value="easy">Easy</option>
            <option value="med" selected>Medium</option>
            <option value="diff">Difficult</option>
        </select><br />
        <button id="btnEnter">Enter</button>

You could see the <select> element is used to add drop down or combo box and we have included four different types of games and three difficulty levels for the user to select. In the type of games, the Puzzle game will be selected by default as we have added the “selected” attribute for that option. Similar is the case with Medium difficulty level.

Add the following lines of code inside the <head> section to check whether the device is ready. Once the device is ready, we will add the event listener to the button for its click event.

            window.onload = function()
                document.addEventListener("deviceready", init, false);
            function init()
                document.getElementById("btnEnter").addEventListener("click",saveData, false);

Now we need to write the saveData function. Of course, you can save the items as 4 different key/value pairs. But, it will be exactly the same as we have done in localStorage tutorial. So, let’s see how to store arrays in the session storage. Once you understand the technique, you can store arrays in local storage as well. We will get the values entered or selected by the user and store the values in an array. Then, we will store the array as a string in the session.

Add the following lines of code after the init function.

function saveData()
                var firstName = document.getElementById("fname").value;
                var lastName = document.getElementById("lname").value;
                var gameType = document.getElementById('type');
                var typeText = gameType.options[gameType.selectedIndex].innerHTML;
                var diffLevel = document.getElementById('difficulty');
                var levelText = diffLevel.options[diffLevel.selectedIndex].innerHTML;
                var details = new Array();
                details = [firstName, lastName, typeText, levelText];
                window.sessionStorage.setItem("info", JSON.stringify(details));
                window.location = "welcome.html";

Here firstName, lastName, typeText and levelText contain the values entered or selected by the user. In fact, the two variables gameType and typeText are used to get the text in the “type” drop down. Similar are diffLevel and levelText. To make it clear, suppose the user selects the value Adventure from the type drop down. If you try to get the game type selected, using document.getElementById('type').value, you will get “advent” (that is the value) and not “Adventure” (that is the text). Again, if you use

document.getElementById('type').selectedIndex, then you will get the value 0 (as it is the first item). So, we used the options array to get the text value selected by the user.

Next we created an array named details and stored the four values, firstName, lastName, typeText and levelText, in it. The issue here is that localStorage only supports strings. So, we used the JSON.stringify method to convert our array into a string. Then, we saved the details array (now a string) in session using setItem method of sessionStorage object. Finally, we redirected the user to a new page, welcome.html.

So, now we need the welcome.html page. Using your text editor, open a new file and add the following lines of code.

<!DOCTYPE html>
        <meta charset="utf-8" />
        <meta name="format-detection" content="telephone=no" />
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
        <script type="text/javascript" src="cordova.js"></script>
        <title>Session Storage</title>
            window.onload = function()
                document.addEventListener("deviceready", init, false);
            function init()
               var retrieveInfo = window.sessionStorage.getItem("info");
               var parsedInfo = JSON.parse(retrieveInfo);
               document.getElementById("info").innerHTML = "Welcome " + parsedInfo[0] + " " +
                                    parsedInfo[1] + "!!! So, you wish to play <b>" + parsedInfo[2] +
                                    "</b> games at " + parsedInfo[3] + " level. Have a great time!!!";
        <div id="info"></div>

This page contains only a <div> element with id=info to display the welcome message. The main thing you have to take care is that after retrieving the data from the session using getItem method, you need to parse it to convert back the string to an array. We first collected the information in retrieveInfo variable and then parsed and stored it inside the parsedInfo variable. Now the parsedInfo is an array with four elements. You just have to fetch the elements using the correct index. I have just appended the retrieved elements to make a meaningful message. Save index.html and welcome.html files. Run your project from the Android Development Environment.

You will get a screen like this:


Enter values in the text boxes and select values from the drop downs. You could see that when you click any of the drop down, the way it appears will be as in a mobile device.


The way it appears will be different based on the configuration of your emulator. In an iOS simulator, the appearance will be entirely different. Once you are ready to click the Enter button, your screen will look like this (of course with different values).


Now click the Enter button and you will get a screen like this:


Now, let us check whether the data still remains after exiting the current session. To check this, select some other app by clicking the MENU and then come back to this app. Just click the Enter button and you will get a screen like this:


The message you see does not contain the values you stored previously. The Puzzle game and Medium level displayed in the message is not the values fetched from the session storage, but just the default values. Thus, it is clear that the data stored in session will be lost once the current session is closed.


In this tutorial, we have created an app that stores data only for a particular session. We have also seen how to store arrays in session storage with the help of JSON.stringify and JSON.parse methods. Similarly, you can store arrays in local storage as well. We have also seen that data stored in the session is lost once the application is closed.

Like us on Facebook