single-head-img

HTML5 Local Storage and Ionic

May 23, 2017

Hello all, here’s tiny tutorial about ionic and HTML5 local storage. After some posts oriented to Ionic framework and WordPress REST API, here’s something about “not so popular” HTML5 thing called Local Storage.

What is HTML Local Storage?

Local storage can be used by web applications to store data locally within the user’s browser. Before HTML5, application data had to be stored in cookies, included in every server request. Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance. Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server. Local storage is per origin (per domain and protocol). All pages, from one origin, can store and access the same data. When we’re talking about browser supporting, HTML5 Local Storage is supported by Chrome (4.0+), Firefox (3.5+), Safari (4.0+), Opera (11.5+) and IE 8+, so it’s really great compatibility.

The localStorage Object

Important: The localStorage object stores the data with no expiration date. To store an object on localStorage we will use setItem function which argument is “key, value” pair:

// Store
localStorage.setItem("key", "value");

 

To get value from local storage we will use getItem function which argument is only the key. So for our example we can use:

// Retrieve
var keyValue = localStorage.getItem("key");

 

There is one example of local storage usage, I’ve used this part of code to test if user opened this site before:

if(window.localStorage.getItem("loggedIn") != 1) {
    // Running for the first time.
    window.localStorage.setItem("loggedIn", 1);
    console.log("First time.");
}else {
    // Already run this site before.
    console.log("Running this for more than one time");
}

 

The sessionStorage Object

The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. When the user close the tab, sessionStorage object ew-new it’s value. Session Storage is using same functions as Local Storage, so you can use setItem and getItem with same arguments, too.

For example, I’ve created Click Counter to get how many times user clicked on specified button:

<!DOCTYPE html>
<html>
    <head>
        <script>
        sessionStorage.setItem("clicked", 0);
        function clickCounter() {
            // Count clicks and store them
            sessionStorage.setItem("clicked", parseInt(sessionStorage.getItem("clicked")) + 1);
            document.getElementById("result").innerHTML = sessionStorage.getItem("clicked");
        }
        </script>
    </head>
    <body>
    <p><button onclick="clickCounter()" type="button">Click me!</button></p>
    <div id="result"></div>
    </body>
</html>

 

removeItem function

If you, for some reasons, want to remove functionality of localStorage object, you can use removeItem function like this:

localStorage.removeItem("key");

 

After this, you will get “undefined” if you try to get object from localStorage.

Usage in Ionic Framework

The greatest thing about those storages is that both of them can be used for ionic framework. Ionic framework is HTML5-based (that info you can firstly get on their facebook official page here). We can use as much of HTML5 functionalities as we need, so don’t hesitate and use them wisely into Ionic famework, also. There is just an simple example of how you can use it:

.factory('sessionService',['$http',function($http){
return {
   set:function(key,value){
      return localStorage.setItem(key,JSON.stringify(value));
   },
   get:function(key){
     return JSON.parse(localStorage.getItem(key));
   },
   destroy:function(key){
     return localStorage.removeItem(key);
   },
 };
}])

 

Conclusion

Local Storage and Session Storage are very powerful tools from HTML5. Many people use cookies instead, but for long-term or session purposes, I suggest to use localStorage. It’s a lot easier and you can use it with web view frameworks, like ionic.

Thanks for reading. Every comment is useful. 🙂

LEAVE A COMMENT