The Web offers variety of APIs to build your app or website. You could access using JavaScript code. These days browsers offer many APIs to developers. In the last article, we read about XMLHttpRequest API and in this article, we will understand Storage APIs available.
Before moving further let us look at the previous articles of the JavaScript series:
Before I dig into storage we will understand key-value pair.
Key-Value pair (KVP)
KVP stores two values together. It is a set of two linked data items; a unique key and some value. This is frequently used in hash, map, dictionary, JSON, configuration files etc. Example – below representation of KVP could be translated in the form of Object in JavaScript.
- var obj = {width: 300, height:200, title: 'Menu'};
Now let’s proceed with Storage API
Web Storage API
When we think about storage we think of Database, Files etc. With HTML5 web storage provides a client-side method for storing information.
The two ways within Web storage are:
- sessionStorage: maintains a storage as long as browser is open, including page reloads and restores. It gets clear when session ends.
- localStorage: same thing like sessionStorage, but persists even when the browser is closed / opened again. This means it has no expiration time.
Note: There was a way in Firefox 9, i.e., globalStorage but it was deprecated after HTML5 introduced this local storage.
Access client-side storage
These are available via Window.sessionStorage & Window.localStorage. Both of these provide access to create, get, modify, delete client-side storage depending upon session or local store.
Facts about client-side storage
Question: How much storage does browser provide?
Answer: Generally, 5MB, 5MB is available for sessionStorage& localStorage respectively.
Question: How can we check the available storage in our browser?
Answer: You can leverage utility to run these tests at your browser and it will show you the output. I conducted test at my browser Chrome 50 & Firefox 45 and both gave same result, i.e., 5 MB.
A misconception
Please note 5MB does not mean 5 million characters are allowed. Developers think that each character occupies 1 byte, which is correct for some programming languages. But JavaScript occupies 2 bytes each character as it stores string on basis on UTF-16.
localStorage
Write localStorage
Below code will write data into localStorage and using setItem() function:
- <script>
- localStorage.setItem("fname", "Sumit");
- localStorage.setItem("lname", "Jolly");
- localStorage.setItem("profile", "http://www.c-sharpcorner.com/members/sumit-jolly");
- </script>
Configure a website in local Web server and run URL: http://localhost:8079/test.html
You can see ‘Local Storage’ content in browser after clicking Resources in Chrome.
If you run on Firefox then it will also create a Local Storage but view is disabled by default. To enable it goto ‘Toolbox options’ and click Storage checkbox.
Aforesaid, localStorage has no expiration and even you close browser it’ll stay there. You can try this and would be able to see data in localStorage of browser.
Read localStorage
You can retrieve data from localStorage using getItem() function. I prefer iterating to KVP.
Example:
- (function() {
- for (var i = 0; i < localStorage.length; i++){
- console.log(localStorage.getItem(localStorage.key(i)));
- }
- })();
Output
Sumit
Jolly
http://www.c-sharpcorner.com/members/sumit-jolly
There are many other functions and properties you can explore like removeItem, clear, length.
sessionStorage
It is same as localStorage with the difference that it is associated with session only. After you close browser window it is gone. I believe if you have more security aspect than go for sessionStorage rather localStorage.
Cookies
For many years, cookies are used to remember user information. So whenever a user visits page his/her information is stored in a cookie. It is also saved as KVP.
A simple cookie can be created like:
- document.cookie = "fname=Sumit";
- document.cookie = "lname=Jolly";
- console.log(document.cookie);
You can check it in browser Resources Developer Tools.
Notice an expiry date is set to Session. The reason we have not defined an expiry date to a cookie, so default is session.
You could do via setting an expiry date alongwith.
- document.cookie = "fname=Sumit; expires=Mon, 15 Aug 2016 12:00:00 UTC";
Here are the differences between three storage types we discussed:
localStorage | sessionStorage | Cookies |
Not added | Not added | Added to every HTTP request |
No expiry | date Expire with session | Has both features i.e., session and you can define expiry date |
Limit of 5MB | Limit of 5MB | Cookies give you a limit of 4096 bytes |
Summary
Now the world is going towards fat client and thin server. With browsers becoming more capable of faster processing of data and powered with various resources, think of client before server for good performance of your web application.