Using Html5 Local storage on mobile devices

In many situations there is a need to store something on the mobile device that can be later retrieved and reused. Typical situation is the offline state where device suddenly loosing internet connection.

To solve this problem we can use HTML5 local storage. It works on all mobile devices with the most popular browsers. Additionally, unlike the cookies the values are not being transmitted from device to the server on each request. They are also persistent across the pages.

In our example we will assume that user sends timesheet data from his mobile device (the files are running locally on the device).
When user sends the data, we store it in local storage trying to send it. If sending is not successful, we keep it in the storage. We also check if we can send the data every time user posts the new form.

 //when DOM is ready
 $(document).ready(function () {

    //try to post saved data every time someone loads page (silent mode)
    trySaveOfflineData(true);

    //if someone saved the form
    var id = getUrlVars()["UserID"];
 
    if (id != null) {
        
        //save in local storage first
        saveData();

        //post local storage data data
        trySaveOfflineData(false);
    }
});

We also need to check if local storage is supported on the mobile device.

 function supportsLocalStorage() {
    //check if device supports local storage
    try {
        return 'localStorage' in window && window['localStorage'] !== null;
    } catch (e) {
        return false;
    }
}

When user saves the data we simply read the values and concatenate it to the single string object. We will read this values later using generic handler in our standard asp.net application located on the remote server.

 function saveData() {
    //read url params from submitted form (we can also use post method instead)
    var userID = getUrlVars()["UserID"];
    var name = getUrlVars()["Name"];
    var comments = getUrlVars()["Comments"];
    var hours = getUrlVars()["Hours"];
    var overtime = getUrlVars()["Overtime"];
    var job = getUrlVars()["Job"];

    var idKey = 'timesheet.' + userID;//set the unique key making sure it belongs to us
    var obj = userID + "|" + name + "|" + comments + "|" + hours + "|" + overtime + "|" + job;

    //save object in local storage
    localStorage.setItem(idKey, obj);

    return true;
}

Every time user loads the page we read values from the local storage and try to post it to our web application. If he gets internet connection we should be able to push our storage data to the server.

 function trySaveOfflineData(silent) {
    // check all keys in local storage
    for (var key in localStorage) {
        
        //check if it our data
        if (key.search('timesheet.') >= 0) {

            var dataObj = localStorage[key]; // get object

            //post it to the server
            postData(SERVER_URL, dataObj, silent);

            //delete item from local storage
            localStorage.removeItem(key);
        }
    }
}

When posting the data we simply use Jquery post method. Next, we read the response from the server as a string and display messages if necessary.

 function postData(url, dataObj, silent) {
    //use Jquery post and send object as a param timesheetObj
    $.post(url, { timesheetObj: dataObj },
                             //get response
                             function (data) {
                                 if (data == "OK") {
                                     if (!silent) { alert("Data has been sent!"); }
                                     return;
                                 }
                                 //if not supports local storage display warning
                                 if (!supportsLocalStorage()) {
                                     if (!silent) { alert("offline mode not supported!"); }
                                     return;
                                 }
                                 //if we got here - it has to be an error 🙂
                                 if (!silent) { alert("Error occurred: " + data); }
                             });
 }

On the server side we use generic handler to process the request. We also need to set headers to avoid Cross-site HTTP request errors.

  public void ProcessRequest(HttpContext context)
  {
        // this is to avoid following error: XMLHttpRequest cannot load https://localhost:58017/WebSite/send.ashx. 
        // Origin https://localhost:58078 is not allowed by Access-Control-Allow-Origin.
        context.Response.AppendHeader("Access-Control-Allow-Origin", "*");  
        context.Response.ContentType = "text/plain";

        try
        {
            var data = context.Request["timesheetObj"];
            var timesheet = data.Split('|');

            var userID = timesheet[0];
            var name = timesheet[1];
            var comments = timesheet[2];
            var hours = timesheet[3];
            var overtime = timesheet[4];
            var job = timesheet[5];
            
            //check and save the data here

        }
        catch (Exception ex)
        {
            context.Response.Write(ex.Message); return;
        }

        context.Response.Write("OK");
    }

Solution I described it’s just a test sample that needs to be converted using PhoneGap before going into production. PhoneGap simply wraps html elements to get desired look on the device. We would also need to apply security measures to avoid fake or duplicated requests etc.

In general I this this is good alternative to creating mobile solution that works only on one platform.

I have included working example below for you tests. Happy coding 🙂
Html5-LocalStorage

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...Loading...